Last line of file/Perl

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: Kevin Buettner
Date:  
Subject: Last line of file/Perl
On Nov 14, 1:50pm, Kevin Buettner wrote:

> On Nov 14, 3:39pm, Mike Starke wrote:
>
> > I need to open a file and just read in the last line, can anyone
> > throw me a bone?
>
> [...] To really do what you want, you'll need to seek to the
> end and then seek backwards reading each character until you find the
> end-of-line character(s) of the penultimate line.


Like so:

#!/usr/bin/perl

while (@ARGV) {
    $filename = shift @ARGV;
    open FH, "<$filename"        or die "Can't open $filename";


    seek FH, -length($/), 2         or die "Can't seek";
    $pos = tell(FH);
    while (seek(FH, --$pos, 0) && ($_ = <FH>) ne $/) {
    $last_line = $_;
    }


    print $last_line;
}