Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re^2: reading several lines in a gulp (iterator)

by LanX (Sage)
on May 01, 2011 at 13:06 UTC ( #902333=note: print w/replies, xml ) Need Help??

in reply to Re: reading several lines in a gulp
in thread reading several lines in a gulp

> I'm sure there are more elegant solutions...

indeed, iterators are easier to maintain!

sub readlines { my ($fh, $count) = @_; my @gulp; push @gulp, scalar <$fh> while $count-- and ! eof $fh; return @gulp; } while ( @lines = readlines(DATA,3) ) { print @lines,"----\n"; } __DATA__ a b c d e


a b c ---- d e ----

alternative iterator:

sub readlines { my ($fh, $count) = @_; my @gulp; while (<$fh>) { push @gulp,$_; last unless --$count; } return @gulp; }

Cheers Rolf

UPDATE: Handling of edge cases like missing $count parameter could be added to the iterators:    $count=1 unless $count;

Maybe $count<=0 should be handled differently...

  • 0 => no iteration
  • -1 => slurp whole file
  • -2 .. => warning
  • Replies are listed 'Best First'.
    Re^3: reading several lines in a gulp (iterator)
    by John M. Dlugosz (Monsignor) on May 01, 2011 at 13:25 UTC
      I like it! Thanks.

    Log In?

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

    How do I use this? | Other CB clients
    Other Users?
    Others avoiding work at the Monastery: (3)
    As of 2023-03-21 17:39 GMT
    Find Nodes?
      Voting Booth?
      Which type of climate do you prefer to live in?

      Results (60 votes). Check out past polls.