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 |