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

Good day/night/morning/holidays/new year/birthday/life :-)

I need to list a logfile. Is there a way to open a file 'from the end'?
The last lines in the file contain the most recent events so those would need to be listed first and I'm not sure there's a way of doing this without reading the whole file into an array and the using negative indexes.

Do I seek() to the end and then backtrack byte-per-byte until I reach a newline, for every line?
Or is there an easier way to open a file and then using the magical <> operator but in reverse?

An other solution would be to add newest lines to the top of the logfile but that would definatly require a complete rewrite of the entire file, everytime. (right?)

Thanks in advance,
CBAS

Replies are listed 'Best First'.
Re: reverse filereading?
by danger (Priest) on Jan 15, 2001 at 22:05 UTC

    Perhaps the module File::ReadBackwards, will be something worth looking into for your problem.

Re: reverse filereading?
by chipmunk (Parson) on Jan 15, 2001 at 22:10 UTC
    I recommend Uri Guttman's module File::ReadBackwards. It is efficient, robust, respects $/, and does exactly what you're looking for!

    The module seeks to the end of the file, then moves backwards through the file reading large blocks of data into a buffer and separating the data into lines. Uri found that to be the most efficient solution.

Re: reverse filereading?
by extremely (Priest) on Jan 15, 2001 at 22:00 UTC
    Look at File::Tail. It should either do what you want or show you how. =)

    --
    $you = new YOU;
    honk() if $you->love(perl)

Re: reverse filereading?
by lemming (Priest) on Jan 16, 2001 at 00:45 UTC
    I just looked at File::ReadBackwards and noted that the cpan.org page doesn't list windows as a tested platform. opening the code does show it makes provisions for windows and my tests on NT 4.0 show that it works.
    Note: It checks your platform for how it handles carriage returns so a Unix file on a windows box will not be handled correctly.
A reply falls below the community's threshold of quality. You may see it by logging in.