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

In reply to Re: Can anyone simplify this code by johngg
in thread Can anyone simplify this code by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.