Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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

by elanajk (Initiate)
on Jul 05, 2001 at 22:14 UTC ( #94192=perlquestion: print w/replies, xml ) Need Help??

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 (Canon) 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] ); }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://94192]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2021-04-20 04:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?