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,
Flexx

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


In reply to Re: while loop over filehandle by Flexx
in thread while loop over filehandle by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.