Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks Is there a way to know in advance that the line read is the last line of a file in perl. If yes how. If no is ther any other alternative. I have tried using stat. but that doesnt work our for me since I need to parse the last line also before i encounter the eof. can anyone help me out Regards, Sid

Replies are listed 'Best First'.
Re: problem accessing file
by jZed (Prior) on Apr 08, 2005 at 15:00 UTC
    If you know the size of the last line in bytes, you can seek to the end of the file and then seek back that number of bytes before reading. Or if you know the number of lines in the file, you can use $. to find the last one. If you don't know either the bytes or lines, you can use File::Tail. Or you can simply declare a variable then loop through the file setting the variable to each line and then at the end of the loop, presto, the variable only holds the last line.
Re: problem accessing file
by sh1tn (Priest) on Apr 08, 2005 at 15:15 UTC
    open FH, $0 or die $!; @_=<FH>;print $_[$#_-2] STDOUT: @_=<FH>;print $_[$#_-2]


Re: problem accessing file
by tlm (Prior) on Apr 08, 2005 at 18:17 UTC

    I am curious: why isn't this good enough for your purposes:

    my $last_line; $last_line = $_ while < FH >; parse( $last_line );
    ? I realize that in this snippet the parsing of the last line is happening after you hit eof, but what I don't see is what exactly you gain from parsing the last line before hitting eof.

    the lowliest monk