Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Reading a file line-by-line from the bottom up

by fx (Pilgrim)
on Jan 08, 2004 at 00:19 UTC ( [id://319669]=perlquestion: print w/replies, xml ) Need Help??

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

Using:

open(FILE, "<some_file.txt"); while(<FILE>) { ## Do some processing... } close(FILE);

I can read a file line-by-line from the top down. How would I go about reading it line-by-line from the bottom up?

Under Linux I suppose it would be fairly easy to have my code read standard input and simply tac (like cat, but in reverse) the file into the script. However, I can't guarantee that tac will be available on all systems where this code will run and would therefore prefer to do it with Perl.

The file in question is large (~600Mb) so I'd rather not read it into memory first :)

Any ideas?

Replies are listed 'Best First'.
Re: Reading a file line-by-line from the bottom up
by runrig (Abbot) on Jan 08, 2004 at 00:27 UTC
Re: Reading a file line-by-line from the bottom up
by davido (Cardinal) on Jan 08, 2004 at 00:28 UTC
    You could have a look at File::ReadBackwards, on CPAN.

    It should do what you're looking for.

    From the docs....

    This module reads a file backwards line by line. It is simple to use, memory efficient and fast. It supports both an object and a tied handle interface.

    It is intended for processing log and other similar text files which typically have their newest entries appended to them. By default files are assumed to be plain text and have a line ending appropriate to the OS. But you can set the input record separator string on a per file basis.

    And an example...

    use strict; use warnings; use File::ReadBackwards; tie *BW, 'File::ReadBackwards', 'log_file' or die "can't read 'log_file' $!" ; while( <BW> ) { # Do some stuff... }

    HTH!


    Dave

Re: Reading a file line-by-line from the bottom up
by ysth (Canon) on Jan 08, 2004 at 00:27 UTC
Re: Reading a file line-by-line from the bottom up
by fx (Pilgrim) on Jan 08, 2004 at 09:39 UTC

    Ah, well, ok, I guess that's one of those d'oh moments. I did check the CPAN listings but there so many I must have missed it.

    Many thanks! :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-20 16:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found