Well, to respond to Merlyn, I started thinking about how to do it after
reading a reply he wrote on clpm that File::Backwards and Tie::File
are good, but not quite the fastest. So I thought, hmmm, how would
I do this? The code is the most straight forward approach I could
come up with. Just start at the EOF and count back byte by byte,
counting newlines, until I satified my $numlines test.
I tested it against the following File::Backwards script on a 100 meg file, and my script was faster by a small amount, plus I don't need
to use a module. I used the system time command to time them.
#!/usr/bin/perl
use File::ReadBackwards;
#usage tailfilebackwards filename numlines
my $filename = shift or die "Usage: $0 file numlines\n";
my $numlines = shift;
$bw = File::ReadBackwards->new($filename) or
die "can't read $filename $!" ;
$count=0;
while(defined($line = $bw->readline)){
push @lines,$line ;
$count++;
if ($count == $numlines){last}
}
@lines= reverse @lines;
print "@lines\n";
exit;
My sample times follow:
For 3 tries -> time tailfilebackwards ARCHIVE 10
real 0m0.078s
user 0m0.040s
sys 0m0.010s
real 0m0.060s
user 0m0.040s
sys 0m0.010s
real 0m0.077s
user 0m0.040s
sys 0m0.000s
###########################################################
For 3 tries -> time tailz ARCHIVE 10
real 0m0.051s
user 0m0.010s
sys 0m0.000s
real 0m0.056s
user 0m0.010s
sys 0m0.010s
real 0m0.056s
user 0m0.010s
sys 0m0.020s
##########################################################
Now I admit that my method is non-portable, so the modular
methods are better in that respect, but time-wise they are not.
If anyone cares to comment on how I might make my method
better, I would appreciate that.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.