Skip to content

Instantly share code, notes, and snippets.

@schwern
Created July 10, 2010 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schwern/471071 to your computer and use it in GitHub Desktop.
Save schwern/471071 to your computer and use it in GitHub Desktop.
#!/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);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment