Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find if it is the last line while reading a file from within a loop in perl

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?

like image 464
Viky Avatar asked Dec 01 '22 12:12

Viky


2 Answers

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

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

like image 143
butterchicken Avatar answered Dec 06 '22 09:12

butterchicken


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.)

like image 39
Telemachus Avatar answered Dec 06 '22 10:12

Telemachus