Question

I am working on a log parsing script using Perl. I am reading the log file as follows:

open(LOGFILE, "$logFile") || die "Error opening log file $logFile\n";                           
while(<LOGFILE>) 
{   
  #Processing statements goes here.
}

Now in processing statements I want to check if the file reading pointer is on the last line. if yes then want to process a condition before exiting.

So the question is from within the while loop which is being used to read the file line by line, How do I find out if it's on the last line?

Was it helpful?

Solution

my $last;
while(<MYFILE>) {
   $last = $_ if eof;
}

Though unless you are doing something with every other line, this is pretty inefficient.

OTHER TIPS

If you only care about the last line, take a look at File::ReadBackwards. It was specifically designed for logfiles and situations where the items of interest are at the end.

Once you install that module, you can pop off the last line only (rather than going through the whole file until it's found) quite easily:

#!/usr/bin/env perl
use strict;
use warnings;
use File::ReadBackwards;

my $fh = File::ReadBackwards->new( 'dir_walk.rb' )
    or die "Can't read 'dir_walk.rb': $!";

my $last_line = $fh->readline;

print $last_line;

Edit: For what it's worth, I would only recommend this if you don't want to look through the whole file. That is, if you are going to read through the entire file no matter what, then this is probably not the best solution. (I am not quite sure from your question whether you only want to check for a specific item in the last line, or if you also care about the rest of the log.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top