Read a file as 4-line chunks I want to extract the file content into chunks with perl. I have prepared some code snippets which read a file content into chunks.
I want to know what is the best way in Perl?

Example-File-Content:

1111
2222
3333
4444
5555
6666
7777
8888
9999
1212
1313
1414
1515


Example1:

#!/usr/bin/env perl
use strict;
use warnings;

open my $fh, '&lt;', 'DUMP' or die $!;

until(grep !defined, my @chunk = map scalar &lt;$fh&gt;, 1 .. 4) {
    print @chunk, "\n";
}


Output: 

1111
2222
3333
4444

5555
6666
7777
8888

9999
1212
1313
1414


Example2:

#!/usr/bin/perl -w
use strict;

open my $fh, '&lt;', 'DUMP' or die $!;

my $i;
my @details;

while(&lt;$fh&gt;) {
    push @details, $_;
    next if ++$i % 4;
    print @details, "\n";
    @details = ();
}


Output:

1111
2222
3333
4444

5555
6666
7777
8888

9999
1212
1313
1414


Example3:

#!/usr/bin/perl -w
use strict;

open my $fh, '&lt;', 'details.txt' or die $!;

sub read_lines {
    my ($fh, $amnt) = @_;
    return unless defined(my $line = &lt;$fh&gt;);
    return (
        $line,
        $amnt &gt; 1 ? read_lines($fh, $amnt - 1) : ()
    );
}

while(my @details = read_lines($fh, 4)) {
    print @details, "\n";
}


Output:

1111
2222
3333
4444

5555
6666
7777
8888

9999
1212
1313
1414

1515
IMHO, the best way is the second example, but with some improvements:

#!/usr/bin/perl
use strict;
use warnings;

open my $fh, '&lt;', 'DUMP' or die $!;
while(&lt;$fh&gt;) {
    print $_;
    print "\n" unless $. % 4;
}


There're no needs to temporary store in an array, and use the $. variable instead of a counter.

$. contains the current line number for the last filehandle accessed, see perlvar

If you want a separte function that returns the chunck:

#!/usr/bin/perl
use strict;
use warnings;

sub getChunck {
    my $file = shift;
    my @chunck;
    open my $fh, '&lt;', $file or die "Unable to open '$file': $!";
    while(&lt;$fh&gt;) {
        push @chunck, $_;
        push @chunck, "\n" unless $. % 4;
    }
    return @chunck;
}

my @chunck = getChunck('DUMP');