Saturday, October 8, 2016

Perl: This script is to read only the last line from the file

This script is in case if you just need to read the last line from the file.

#!/usr/bin/perl
#############################################
#
#Script to read the last line of the file
#
##############################################

my $last_line;   #Define a variable

#store the filename into a variable
$fname = 'filename';
open FH, $fname;
  while () {
    chomp;               #removes any emptylines present between the lines
    $last_line = $_;
#removes any emptylines present between the lines although not required as chomp already doing the same work
    $last_line =~ s/^\s*|\s*$//g;  
  }
  close FH;
#This line will print only the last line after iterating through the eof when while condition matches and comes out with the last line only. 
print "$last_line\n";

No comments:

Post a Comment