in reply to while loop over filehandle

Hi monks!

First of all, do not use \n\r to cope with/match foreign systems' newlines! chomp appears to be better but it's not (that is, it works only for files in a somewhat compatible format).

Please, please read this node for an expanation of this.

Another trick when iterating over something of arbitrary size, while spitting something out (or doing whatever) at each chunk of data of a given size, use the modulo function (%). This function repeatedly goes zero whenever the chunk size is hit, and is nonzero in between. Here's my try on this:

# tested, but might not exactly match what anonymous # was doing (added newline output after each chunk, # blank after comma seperator,...) use constant CHUNK_SIZE => 20; open(FILE, $filename) or die "Can't open $filename: $!\n"; while(<FILE>) { s/\012(?:\015)?|\015(?:\012)?//g; push @users, $_; unless($. % CHUNK_SIZE) { print join(', ', @users), "\n"; @users = (); } } print join(', ', @users); # Output what's left. close FILE;

Of course one could also say unless(@users == CHUNK_SIZE) in this case (since scalar @users actually works as a subcounter here). But, oh well, I just wanted to demonstrate a neat trick. But when you want to interrupt a loop every few passes, using only a total counter modulo really comes in handy. ;) When you think "do x on every nth line/iteration/pass", think modulo.

So long,

Updated: Added last paragraph after first submitting. Made braces in s/// noncapturing (++diotalevi).