Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: read a file in both directions

by TedPride (Priest)
on Jun 01, 2006 at 05:27 UTC ( [id://552978]=note: print w/replies, xml ) Need Help??


in reply to read a file in both directions

This is ridiculously easy if you don't care about memory:
open($handle, 'test.dat'); while (<$handle>) { chomp; last if !$_; } chomp(@data = <$handle>); close($handle); for (reverse @data) { print $_, "\n"; }
But you may want to use a more memory-efficient method:
open($handle, 'test.dat'); while (<$handle>) { chomp; last if !$_; } while (<$handle>) { chomp; push @data, $_; } close($handle); for ($i = $#data; $i > -1; $i--) { print $data[$i], "\n"; }
And then there's always the really memory-efficient method (which I'm not supplying code for here), which would involve finding the position in the file of the first blank line (keep track of current position by adding up line lengths), then going to the end of the file and working back in chunks of x bytes. This gets a lot more messy and complicated, and I sadly don't have time right now to write up a working code sample.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-26 04:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found