in reply to Re^2: Does Perl support a given number of replacements ?
in thread Does Perl support a given number of replacements ?
If I run this code, I might expect 'aaBaaCaaDaEaFa' to be printed, but I get 'aaaaBaCaDaEaFa' instead. This is because the regex of the substitution does not 'remember' its position in the string being searched, but instead starts from the beginning of the string on each invocation. So, if the substituted portion of the string contains anything that may be matched by the regex, then it, and not anything further along in the string, is what will be (repeatedly) replaced.>perl -wMstrict -le "my $x = 'aBaCaDaEaFa'; $x =~ s/a/aa/ for 1 .. 3; print $x; "
jwkrahn's reply Re: Does Perl support a given number of replacements ? shows a way around this.
Update: Improved first example and changed pertinent discussion, removed a second example as no longer offering greater clarity.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Does Perl support a given number of replacements ?
by ig (Vicar) on Jun 06, 2009 at 09:05 UTC | |
by johngg (Canon) on Jun 06, 2009 at 12:47 UTC |