My first thought is to use a combination of $& (which holds "the string matched by the last successful pattern match") and index.

Update: pos, as btrott points out, is the right answer. My idea won't find multiple instances of your search string per target string (and besides, why re-invent a perfectly round wheel?).

my $R = 'Russ Ethan Jason Eric'; $R =~ /Ethan/; print index($R, $&), "\n"; $R =~ /Eric/; print index($R, $&), "\n";
Prints:
5
17

So, adapting my first code to the better answer, this is how I might look in multiple strings for multiple patterns:

my @R = ('Russ Ethan Jason Eric JAPH', 'JAPH vroom Ozymandias neshura +Russ'); for (my $i = 0; $i != @R; $i++){ while ($R[$i] =~ /Russ|JAPH/g){ print "Found $& in string $i at: ", pos($R[$i]) - length $&, "\n"; } }
Prints:
Found Russ in string 0 at: 0
Found JAPH in string 0 at: 22
Found JAPH in string 1 at: 0
Found Russ in string 1 at: 30

Russ
Brainbench 'Most Valuable Professional' for Perl


In reply to RE: index with regex by Russ
in thread index with regex by Dogg

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.