Skip navigation.
Your source for Perl tips, howto's, faq and tutorials
( categories: )

In several situations you may need to read a text file backwards (the typical case is when you need to parse log files). The best way to do this depends of the size of the file:

-- Small file

If the file is small enough, you can read it entirely in memory and put it into an array.


open FILE "<file.txt" or die "can't read file: $!\n";
@backwards = reverse ;

-- Large file

If the file is big, then the best approach is to use the File::ReadBackwards module. This module is fast and memory efficient, the only drawback is that it is not included in the standard perl installation, you have to install it from CPAN.


use File::ReadBackwards;
$fh = File::ReadBackwards->new('file.txt') or
die "can't read file: $!\n";
while ( defined($line = $fh->readline) )
  print $line ;