Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: while loop over filehandle

by Flexx (Pilgrim)
on Sep 23, 2002 at 14:08 UTC ( #200098=note: print w/replies, xml ) Need Help??

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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://200098]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2021-03-01 23:36 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (28 votes). Check out past polls.