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