Forum Moderators: coopster & phranque

Message Too Old, No Replies

Getting Line number in perl

Perl

         

Marianand

3:20 am on Aug 17, 2006 (gmt 0)

10+ Year Member



How to return a line number from a text file in perl?

lexipixel

5:09 am on Aug 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Your question is sketchy, so I'll give a basic idea of "counting lines" (in a text file) using Perl.

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?

perl_diver

6:24 am on Aug 17, 2006 (gmt 0)

10+ Year Member



$. is the input file line number variable:




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);


coopster

9:18 pm on Aug 19, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



A couple of options for you, and welcome to WebmasterWorld, Marianand :)