Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to print last line of file?

Status
Not open for further replies.

billbose

Programmer
Jan 15, 2001
66
US
How to print last line of file?

The Perl cookbook uses this method:
@lines = <FILE>;
$lastline = pop @lines

However the above method requires the file to be loaded completely into an array(memory) and is not suitable for large files.
Tie::File module cannot also be used here since I am using version 5.6 now.
Is there any other option to read the last line without the memory hog.
 
If I want the easy way out, I probably will do:

Code:
$filename = "test.txt";
$lastLine = `tail -n 1 $filename`;
 
Code:
open(FILE,'file.txt');
while (<FILE>)
 print if eof;
}
close(FILE);
 
I think you may find that the tail method is quicker especially for large files - I don't think that tail actually reads the whole file, it's a bit smarter than that...
 
I agree, tail is probably better, but this is the perl forum after all. Posting non-perl solutions in the perl forum should come with a disclaimer. ;)
 
I agree with the reason for tail too! However, I prefer to do it with a module:

Code:
#!/usr/bin/perl -w
use strict;

use File::ReadBackwards;

my $bw = File::ReadBackwards->new( 'file.txt' ) or
                        die "can't read 'file' $!" ;

print $bw->readline;

Just my 2 cents!

X
 
hehehe.... should have known there would be a module for reading a file backwards! [dazed]

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top