Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: reading several lines in a gulp

by LanX (Saint)
on Apr 29, 2011 at 17:31 UTC ( [id://902047]=note: print w/replies, xml ) Need Help??


in reply to reading several lines in a gulp

$. and eof should help
my $count=3; while (<DATA>) { next if ($.-1) % $count and ! eof; print @gulp; print "-----\n"; @gulp=(); } continue { push @gulp,$_ } __DATA__ a b c d e f g h

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

Cheers Rolf

Replies are listed 'Best First'.
Re^2: reading several lines in a gulp (iterator)
by LanX (Saint) on May 01, 2011 at 13:06 UTC
    > 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
      I like it! Thanks.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-03-29 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found