HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Read a file as 4-line chunks

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
chunksfilelineread

Problem

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, ', 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, ') {
    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, ');
    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

Solution

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

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

open my $fh, ') {
    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, ') {
        push @chunck, $_;
        push @chunck, "\n" unless $. % 4;
    }
    return @chunck;
}

my @chunck = getChunck('DUMP');

Code Snippets

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

open my $fh, '<', 'DUMP' or die $!;
while(<$fh>) {
    print $_;
    print "\n" unless $. % 4;
}
#!/usr/bin/perl
use strict;
use warnings;

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

my @chunck = getChunck('DUMP');

Context

StackExchange Code Review Q#163387, answer score: 4

Revisions (0)

No revisions yet.