Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to know the position of a character the regular expression matches last time. For ex:
$_ = "abcdmefg"; $_ = /m/; print "$&\t$`\t$'\n";
It prints: m abcd efg
The above printed matched, prematch and after match. But I like to know the position of the charactr 'm' in the string. Then I used while loop like this:
$_ = "abcdmefg"; while(m/m/g) { print "matched 'm' at ",pos,"\n"; }
Then it prints: matched 'm' at 5. Is there anyway to print the position without while loop? I treid to print using pos in the first example, but does not work. Can you pl. help me? Thanks Ashok

Replies are listed 'Best First'.
Re: position of the last match in RE
by chipmunk (Parson) on Mar 01, 2001 at 08:30 UTC
    In order for pos to remain set, you need to use the /g modifier on the regex. This is why the snippet with the while loop works. So, just use /g without the while loop:
    $_ = "abcdmefg"; if ($_ =~ /m/g) { print "matched 'm' at ",pos,"\n"; }
    However, if you're just looking for fixed substrings, you may prefer to use index instead:
    $_ = "abcdmefg"; if (($pos = index($_, 'm')) >= 0) { print "found 'm' at ", $pos, "\n"; }
    Keep in mind that pos returns the location where the previous match ended, while index returns the location where the substring begins. Thus, these two snippets give 5 and 4 respectively.
Re: position of the last match in RE
by chromatic (Archbishop) on Mar 01, 2001 at 08:30 UTC
    The while part isn't what sets pos, it's the /g modifier on a match. Simply say:
    $_ = "abcdmefg"; m/m/g; print "Matched 'm' at ", pos, "\n";
    If you don't need to match a full regex, you can use the index or rindex functions.