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, '<', 'DUMP' or die $!;
until(grep !defined, my @chunk = map scalar <$fh>, 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, '<', 'DUMP' or die $!;
my $i;
my @details;
while(<$fh>) {
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, '<', 'details.txt' or die $!;
sub read_lines {
my ($fh, $amnt) = @_;
return unless defined(my $line = <$fh>);
return (
$line,
$amnt > 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