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

How do I read a file line by line in reverse order (from EOF to start of file)

Originally posted as a Categorized Question.

  • Comment on How do I read a file line by line in reverse order (from EOF to start of file)

Replies are listed 'Best First'.
Re: How do I read a file line by line in reverse order (from EOF to start of file)
by particle (Vicar) on Jul 05, 2001 at 23:03 UTC
Re: How do I read a file line by line in reverse order (from EOF to start of file)
by swngnmonk (Pilgrim) on Jul 05, 2001 at 23:58 UTC
    If you're on a unix (at least Linux) system, you can use the command 'tac' to reverse the lines in a file. so:
    $/ = "\n"; open(REVERSE_FILE, "|/usr/bin/tac $filename"); while (<REVERSE_FILE>) { print "$_\n"; } close REVERSE_FILE;
      I will put the pipe at the end:  "/usr/bin/tac $filename |"
Re: How do I read a file line by line in reverse order (from EOF to start of file)
by kryberg (Pilgrim) on Oct 23, 2002 at 16:21 UTC
    open( FILE, "<$file_to_reverse" ) or die( "Can't open file file_to_reverse: $!" ); @lines = reverse <FILE>; foreach $line (@lines) { # do something with $line }
    Reference Chapter 8 of the Perl Cookbook.
Re: How do I read a file line by line in reverse order (from EOF to start of file)
by jdporter (Paladin) on Jul 07, 2006 at 13:13 UTC
    You could use File::ReadBackwards. Even better, imho, would be to use Tie::File, which maps the lines of a file into an in-memory array; then you'd simply traverse that array in descending index order.
    use Tie::File; tie my @lines, 'Tie::File', $filename; for my $i ( reverse 0 .. $#@lines ) { do_something_with( $lines[$i] ); }