This subroutine takes a file name and a line count (N) and will return an open filehandle with its read pointer set to N lines before the end of the file. This differs from implementations (like that in PPT) because the entire file is not read -- it reads backwards from the end. It's a quickie so there's no buffering as in GNU's tail(1), but that can easily be remedied. Sample usage:
my $g=lastn("/usr/dict/words", 400);
print while(<$g>);
It was coded to grab the last few bits of a gigantic logfile we use here and may not be suitable for your needs. Enjoy.
sub lastn {
my($file, $lines)=@_;
my $fh;
$lines++;
if (! open($fh, $file) ) {
print "Can't open $file: $!<P/>";
return;
}
binmode($fh);
sysseek($fh, 0, 2); # Seek to end
my $nlcount=0;
while($nlcount<$lines) {
last unless sysseek($fh, -1, 1);
sysread($fh, $_, 1, 0) || die;
$nlcount++ if ( $_ eq "\n");
last if $nlcount==$lines;
last unless (sysseek($fh, -1, 1));
}
seek($fh, sysseek($fh, 0, 1), 0) || warn;
$fh;
}
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.