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

Hi,

Does anyone know if there is a way to read in a file from the bottom?

For example, I want to read in the maillog and only get the last 10 messages, seems a shame to have to go through the whole thing just for that last 10.

Cheers,
Reagen

Replies are listed 'Best First'.
Re: Read File in reverse
by davido (Cardinal) on Jun 05, 2004 at 07:23 UTC
    There is File::ReadBackwards...

    I kind of like the tied filehandle method with that module:

    use File::ReadBackwards; tie *BW, 'File::ReadBackwards', 'log_file' or die "can't read 'log_file' $!" ; while( <BW> ) { print ; }

    You could also use Tie::File and just loop over indices of -1, -2, -3, -4, etc.

    Update: Here's an example of the Tie::File method.

    use Tie::File; tie my @array, 'Tie::File', 'log_file' or die "can't read 'log_file' $!"; for ( 1 .. @array ) { $_ = -$_; print $array[$_]; }

    Note that when counting indeces from the end going backward with an array, the last element starts at -1, not 0, and the first element will be -@array, not -$#array. Just a possible gotcha to watch out for.


    Dave

Re: Read File in reverse
by PodMaster (Abbot) on Jun 05, 2004 at 07:51 UTC
      I must be blind as a bat.
      I'm kinda new to perlmonks and never even saw the search facility 8-}
      Thanks PodMaster.
Re: Read File in reverse
by davidj (Priest) on Jun 05, 2004 at 07:26 UTC
    The following code will fill an array with the lines of a file in reverse order:

    open(FILE, "<myfile.txt"); @file = reverse <FILE>; foreach (@file) { #process line }
    This will process the file from the last line to the first line.

    hope this helps,
    davidj
      But then you have read the whole file.

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law