in reply to Incremental replacement by regex

use strict; use warnings; my $str = "This example could be another example where the example is +the example I wanted"; my $i = 0; $str =~ s/example/'example_'.++$i/eg; print "$str\n";
Gives:
This example_1 could be another example_2 where the example_3 is the e +xample_4 I wanted
At the end of the substitution statement, the 'e' executes the code and the 'g' repeats the substitution for the next occurrence of the string. The ++ is the prefix operator, so it is executed before the rest of the statement.

Replies are listed 'Best First'.
Re^2: Incremental replacement by regex
by markdibley (Sexton) on Feb 21, 2011 at 13:43 UTC
    :-)

    I was sure I tried single quotes. But it was the e modifier that I needed. Thanks

    This was my effort in the end

    my $t = "This example could be another example where the example is th +e example I wanted\n"; my $count = 0; while($t =~ /example\s/){ my $example = "example_".++$count; $t =~ s/(example\s)/$example /; print $t; } print $t;
      The 'g' in my example removes the need for the loop. One slightly pedantic comment on your code, you use \s and you should remember that it matches all whitespace, including a new-line. So, for example:
      my $t = "This example could be another example where the example is th +e example I wanted, for example\n";
      removes the trailing "\n" and replaces it with a space, which is probably not what you want.