Count lines in a file in Perl

Home > Search
  by

$. is the default Perl variable to count the number of lines in a file.

my $file = "/path/to/file.txt";
open(FH, '<', "$file") or die "cannot open $file $! \n";

my $count = 0;
while (<FH>) {
  $count = $.;
}

close(FH);

print "$count\n";

 

To count the number of lines in a file that contain the text "Hello World".

my $file = "/path/to/file.txt";
open(FH, '<', "$file") or die "cannot open $file $! \n";

my $count = 0;

while (<FH>) {
  $count++ if /Hello World/;
}

close(FH);

print "$count\n";

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments