tags:

views:

56

answers:

3

Hello all,

How can I make Perl to tell me the character number of a match, for example in a text file I have:

CHI (3) - NSH (1)        
DAL (4) - CHI (3)        
VAN (3) - CHI (2)    

Want I want to get is for CHI the character number in which appears, for example:

Line 1: 0
Line 2: 9
Line 3: 9

Any ideas or hints?.

+3  A: 

see perldoc -f index

ghostdog74
+3  A: 
use strict;
use warnings;
use English qw<$INPUT_LINE_NUMBER>;

open my $fh, '<', '/path/to/file/I/want' or die "Could not open file!";
while ( <$fh> ) {
    printf "Line %d: %d\n",  $INPUT_LINE_NUMBER, index( $_, 'CHI' );
}
close $fh;
Axeman
+1  A: 

Index solutions as posted here are fine, but for learning purpose, you could also use a regular expression, eg.:

...

while( <$fh> ){
    /CHI/g && print "Line $.: $-[0]\n" 
}

...

would print your desired output. This would even make a fancy one-liner:

$> perl -lne '/CHI/g && print "Line $.: $-[0]"' data.txt

Regards

rbo

rubber boots