This short sub takes a *FILEHANDLE and integer 'n' as arguments and returns the next 'n' lines from the file as an array. It returns undef at EOF so can be used in a while loop as shown.
sub get_n_lines { local *FH = shift; my $n = shift; my @lines; for (1..$n) { my $line = <FH>; push @lines, $line if defined $line; } return @lines; } while (my @lines = get_n_lines(*DATA, 5)) { print "Got:\n", @lines , "\n"; } __DATA__ line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10 line 11 line 12 line 13 line 14 line 15 line 16 line 17 line 18

Replies are listed 'Best First'.
Re (tilly) 1: Get next 'n' lines from a file
by tilly (Archbishop) on Aug 18, 2001 at 21:58 UTC
    I would use the list-oriented nature of Perl and write the above as:
    sub get_n_lines { my $fh = shift; grep defined($_), map {scalar <$fh>} 1..(shift); }
    However before using this I would think carefully about whether I was ever going to read from a tty like STDIN tends to be. Try it with STDIN. Sure you get undef when the person indicates that they are done, but as you continue trying to read on the handle, it tries to read again.

    For the vast majority of things I might use a function like the above for, that doesn't matter. But if I was in one of the remaining fraction of situations I would prefer to manually track whether or not I had hit the end of the file yet. (Issuing calls to eof can also trigger more reads.)

    In fact the best general strategy that I know of for handling this kind of problem is to encapsulate the stream of a data into a structure that always keeps one row of data pre-fetched. Sure it is a lot of conceptual overhead to set that up. But it seems to work better in the end.