File::ReadBackwards has similar, but not quite the same, functionality. Rather than seeking and reading one character at a time, though, it'd be more efficient in general to read larger chunks, like File::ReadBackwards does. Perhaps like so...and autovivifing filehandles is only compatible with 5.6+, so I changed that also to be backward compatible:
sub lastn { my($file, $lines, $bufsiz)=@_; $bufsiz ||= 1024; # Changed FH to STDOUT to avoid warning my $fh = \do { local *STDOUT }; $lines++; if (! open($fh, $file) ) { print "Can't open $file: $!<P/>"; return; } binmode($fh); my $pos = sysseek($fh, 0, 2); # Seek to end my $nlcount=0; while($nlcount<=$lines) { $bufsiz = $pos if $bufsiz > $pos; $pos = sysseek($fh, -$bufsiz, 1); die "Bad seek: $!" unless defined $pos; my $bytes = sysread($fh, $_, $bufsiz, 0); die "Bad read: $!" unless defined $bytes; $nlcount += tr/\n//; $pos = sysseek($fh, -$bufsiz, 1); die "Bad seek: $!" unless defined $pos; last if $pos == 0; } seek($fh, sysseek($fh, 0, 1), 0) || warn; <$fh> for $lines..$nlcount; $fh; }
Update: It does work when requesting more lines than the file contains, though I fixed it to work with various buffer sizes. I don't think a 20000% speed improvement (for tailing 400 10 byte lines) is 'too much' optimization :-) It does miscount if the last line does not have a line feed, though do you actually count that as a line or not? Besides, your's 'miscounts' in that situation also.

In reply to Re: Last N lines from file (tail) by SpongeBob
in thread Last N lines from file (tail) by clintp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.