in reply to Can anyone simplify this code

You can let the regular expression do the work of finding where the word is and printing it's positions. Doing a global match in an empty while loop, it uses the @- array which records the start positions of "last match", see also @+ for end positions. It also uses a regular expression code block (?{...}) to print the position once the match has been found.

use strict; use warnings; use re q{eval}; my $word = q{test}; my $rxWord = qr{\b$word\b}; # This is the one the does the work. # my $rxWordPos = qr{\b($word)\b(?{print $-[0], q{ }})}; while (<DATA>) { next unless m{$rxWord}; print qq{Match found on line $., column }; while (m{$rxWordPos}g) {;} print qq{\n}; } __END__ This is a test from tester okay nothing message test center test test in proress ... test one test two a tester in this line

Here's the output

Match found on line 1, column 10 Match found on line 3, column 8 20 Match found on line 4, column 0 20 29

I hope this is of use.

Cheers,

JohnGG

Update: Simpler version eliminating the regular expression code block.

use strict; use warnings; my $word = q{test}; my $rxWord = qr{\b($word)\b}; while (<DATA>) { next unless m{$rxWord}; print qq{Match found on line $., column }; while (m{$rxWord}g) { print qq{$-[0] }; } print qq{\n}; } __END__ This is a test from tester okay nothing message test center test test in proress ... test one test two a tester in this line

Replies are listed 'Best First'.
Re^2: Can anyone simplify this code
by Anonymous Monk on Jan 11, 2007 at 12:35 UTC
    Thanks a lot for your help and solution