The following will take a file name "fruit.txt" that contains;
Mary likes apples.
Joe doesn't like fruit.
Bill likes bananas.
Oscar likes pineapple.
..and count the number of lines it contains. NOTE: a "line" is considered any amount of text up to a CR/LF character.
#
$f = "fruit.txt";
$n = "0";
open (TXT,"$f");
seek (TXT,0,0);
while ($line = <TXT>) {
$n++;
print "$n). $line<br>\n";
}
close (TXT);
print "There are ($n) lines in the file '$f'.<br>\n";
#
..and return the following output:
1). Mary likes apples.
2). Joe doesn't like fruit.
3). Bill likes bananas.
4).
5). Oscar likes pineapple.
There are (5) lines in the file 'fruit.txt'.
NOTE: the fourth line was blank, but had a CF/LF, so it was counted... There are methods of using perl to be more precise, to exclude "blank" lines, or to count only until a criteria is met.
Is this what you were looking for?
open(FH,'foo.txt') or die "$!";
while (<FH>) {
print $.;
}
close(FH);
so you can use $. to get the line number and for other reasons.
my $search = 'foo';
open(FH,'foo.txt') or die "$!";
while (<FH>) {
return($.) if (/$search/); #returns line number
}
close(FH);