public

  • Download Gist
Tie::File vs simple loop to read range
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#!/usr/bin/perl
 
use strict;
use warnings;
 
use Benchmark qw(cmpthese);
use Tie::File;
use Fcntl 'O_RDONLY';
 
sub read_range {
my($file, $start, $end) = @_;
 
open my $fh, "<", $file or die $!;
 
my @lines;
while (<$fh>) {
last if $. > $end;
push @lines, $_ if $. >= $start;
}
 
return \@lines;
}
 
my $file = "/usr/share/dict/words";
my($lines) = split /\s+/, `wc -l /usr/share/dict/words`;
my $start = int rand $lines;
my $end = $start + int rand $lines - $start;
 
print "Total lines: $lines, start: $start, end: $end\n";
 
cmpthese shift || -3, {
read_range => sub {
read_range($file, $start, $end);
},
tie_file => sub {
my @file;
tie @file, "Tie::File", $file, mode => O_RDONLY;
my @lines = @file[$start..$end];
},
tie_file_object => sub {
my $file = Tie::File->TIEARRAY($file, mode => O_RDONLY);
my @lines;
push @lines, $file->FETCH($_) for ($start..$end);
}
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.