The best way to do that is to count the number of new line characters in the file. An example for the same is given below:

$lines = 0;
open(FILE, $filename) or die “Can’t open `$filename’: $!”;
while (sysread FILE, $buffer, 4096) {
$lines += ($buffer =~ tr/\n//);
}
close FILE;

If your text file doesn’t end with a new line then it’s not really the best way. It will reports fewer lines than are present in the file.
One more way by which you can do this is :

open (FILE, $ARGV[0]) or die “Can’t open ‘$ARGV[0]’: $!”;
$lines++ while ();
close FILE;
print “$lines\n”;

If you enjoyed this post, make sure you subscribe to my RSS feed!!!!

No related content found.