I have a below input file which contains:


I want to count the no of lines and go to the last line of the file and check "999". If it matches then it will proceed to the next step or else it will throw an error message. Currently the last line of my input file is having "998" so it will throw an error message. How can i do this in Perl. Can someone help me in resolving the issue?

My current code is having below

open(FILE, "<deep.txt") or die "Could not open file: $!";

my $lines = 0;

while (<FILE>) {
if($Number =~ m/\d{1,3}/){

     $N = $Number;
print "$N";

print "The no of lines present is $lines \n";

Not entirely sure, but this might help

use strict;
use warnings;

my $fname = "deep.txt";
open(my $fh, "<:encoding(ASCII)", $fname) || die "cannot open $fname for reading";

my $num = 0;

    $num = substr $_, 0, 3 if eof;
close($fh) || warn "cannot close $fname";

print "Oops, last line doesn't start with 999!\n" if $num != 999;

The eof check helps to know if it is the last line of file being read

The while loop can also be shortened to one-line:

eof and $num = substr $_, 0, 3 while(<$fh>);

Further reading:


Using awk:

awk 'END { if ($0 !~ /^999/) print "error"; else printf("Lines in file: %d\n", NR) }' file

If the last line of the file does not start with 999 the string error will be displayed. Otherwise the number of lines in the file will be displayed in a short message.

The same thing with Perl:

perl -ne '$line=$_; END { if ($line !~ /^999/) { print "error\n" } else { printf "Lines in file: %d\n", $. } }' file

The script (beautified):

$line = $_;

    if   ( $line !~ /^999/ ) { print "error\n" }
    else                     { printf "Lines in file: %d\n", $. }

This sets $line to the current line of input.

The END block is executed when no further input is available. It tests whether the last $line begins with 999 or not and either prints an error or the number of lines. The $. variable is a special Perl variable that corresponds to NR in awk (the number of lines/records read).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.