Quite right!!
I experimented with the g option, \G and pos() but they don't work with substitutions as they do with matches and in the end I couldn't find any RE based solution simpler than jwkrahn's that handles replacements that match the search pattern.
But I find REs difficult enought to understand without embeded code, so I came up with the following alternative which may have merit in some situations. It works for the examples you provided but it's not obvious that its doing replacement and the third argument to split is one more than the number of replacements, so it's certainly not ideal.
my $s1 = 'abaacaa'; my $s2 = 'abcdefg'; $s1 = join('aa', split('a', $s1, 4)); $s2 = join('aa', split(/[abcedfg]/, $s2, 4)); print "$s1\n"; print "$s2\n";
In reply to Re^4: Does Perl support a given number of replacements ?
by ig
in thread Does Perl support a given number of replacements ?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |