Hi, jmclark -
The question you ask is, I think, one that everyone working with regular expressions has at some stage. As GrandFather already explained, the problem is due to the behaviour of Perl's regular expression engine.
The normal and idiomatic way to avoid this kind of undesired interference of the match position would be to write the checks for regular expression match as follows:
$gw="abcdefgh";
if ( ( my $a = $gw ) =~ m/abc/ig){
print pos( $a ), ": abc\n";
}
if ( ( my $b = $gw ) =~ m/cde/ig){
print pos( $b ), ": cde\n";
}
if ( ( my $c = $gw ) =~ m/defgh/ig){
print pos( $c ), ": defgh\n";
}
if ( ( my $d = $gw ) =~ m/gh/ig){
print pos( $d ), ": gh\n";
}
if ( ( my $e = $gw ) =~ m/fg/ig){
print pos( $e ), ": fg\n";
}
Effectively, you are thus copying the contents of
$gw into the variables
$a, $b ... and are not directly checking for the match of
$gw anymore. This approach will then return what you had initially expected:
3: abc
5: cde
8: defgh
8: gh
7: fg
Hope this helps.
Regards -
Pat
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.