argv has asked for the wisdom of the Perl Monks concerning the following question:
I also tried using combinations of uses that start with m// in the "while" loop, but using s/// inside the block to modify the string, and then reset the regex position using pos, but again, nothing works. here's sample code:
my $string = "abc abc abc abc"; my $x = 1; while ($string =~ /abc /ig) { my $i = pos($string); $string =~ s/(abc) /$1 def($x)/; print "$string\n"; pos($string) = $i + 6; } print "\nDone. string = '$string'\n";
The desired result should look like this:
abc def(1) abc def(2) abc def(3) abc def(4)
Instead, it produces "abc def(3)def(2)def(1)abc abc abc" and the reason is obvious: the regex always starts back at 0, and it does this no matter what I do. (The above sample code is but one of a variety of attempts.)
In addition to someone solving the specific problem with the code, I'd like a more specific explanation for what the perl rules are concerning progressive matching and the use of substitutions. Is it different than m//? Is it undefined? Is there a specific method documented that I'm not seeing? And why doesn't the above pos call set the position accordingly? UPDATE: Incidentally, I know I can get what I want using this code:
while ($string =~ s/(abc) ([^d])/$1 def($x) $2/i) ...
The point is to understand the proper way of doing progressive matching with substitutions... my so-called 'workaround' won't work in the actual program I'm using, as I can't be sure what the next letter(pattern) would be after the 'abc' match.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Progressive matching w/substitutions
by ikegami (Patriarch) on Aug 09, 2008 at 04:35 UTC | |
by argv (Pilgrim) on Aug 09, 2008 at 16:27 UTC | |
by ikegami (Patriarch) on Aug 09, 2008 at 17:18 UTC | |
by argv (Pilgrim) on Aug 10, 2008 at 17:09 UTC | |
by tye (Sage) on Aug 10, 2008 at 17:17 UTC | |
| |
|
Re: Progressive matching w/substitutions
by dreadpiratepeter (Priest) on Aug 09, 2008 at 04:19 UTC | |
|
Re: Progressive matching w/substitutions
by JStrom (Pilgrim) on Aug 09, 2008 at 04:23 UTC | |
by broomduster (Priest) on Aug 09, 2008 at 10:27 UTC | |
by ikegami (Patriarch) on Aug 09, 2008 at 10:33 UTC | |
by broomduster (Priest) on Aug 09, 2008 at 10:50 UTC | |
by argv (Pilgrim) on Aug 09, 2008 at 16:47 UTC |