开发者

Character number of match in Perl

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?.


see perldoc -f index


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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜