http://qs1969.pair.com?node_id=902333


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

prints

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.