in reply to Progressive matching w/substitutions

1:
my $string = "abc abc abc abc"; my $x = 1; while ( $string =~ /abc /ig ) { my $i = pos($string); substr( $string, $-[0], $+[0]-$-[0]) =~ s/(abc) /$1 def($x)/; print "$string\n"; pos($string) = $i + 6; } print "\nDone. string = '$string'\n";
2:
my $string = "abc abc abc abc"; my $x = 1; while ( $string =~ /(?=abc )/ig ) { my $i = pos($string); $string =~ s/\G(abc) /$1 def($x)/; print "$string\n"; pos($string) = $i + 6; } print "\nDone. string = '$string'\n";

Replies are listed 'Best First'.
Re^2: Progressive matching w/substitutions
by broomduster (Priest) on Aug 09, 2008 at 10:27 UTC
    Neither of those produces the desired output for me. $x is never incremented. Since you require a space at the end of the string-to-be-substituted, there is no substitution after the last abc, and the desired spacing in the output is wrong:
    abc def(1)abc abc abc abc def(1)abc def(1)abc abc abc def(1)abc def(1)abc def(1)abc Done. string = 'abc def(1)abc def(1)abc def(1)abc'

    Putting $x++; in your while loop after the substitution will fix the former, but not the latter.

    Following on the other examples in this thread, one possibility is the following:

    1:

    my $string = "abc abc abc abc"; my $x = 1; # while ( $string =~ /abc /ig ) { while ( $string =~ /abc/ig ) { my $i = pos($string); # substr( $string, $-[0], $+[0]-$-[0]) =~ s/(abc) /$1 def($x)/; substr( $string, $-[0], $+[0]-$-[0]) =~ s/(abc)/"$1 def(" . $x++ . +")"/e; print "$string\n"; pos($string) = $i + 6; }

    2:

    my $string = "abc abc abc abc"; my $x = 1; # while ( $string =~ /(?=abc )/ig ) { while ( $string =~ /(?=abc)/ig ) { my $i = pos($string); # $string =~ s/\G(abc) /$1 def($x)/; $string =~ s/\G(abc)/"$1 def(" . $x++ . ")"/e; print "$string\n"; pos($string) = $i + 6; } print "\nDone. string = '$string'\n";

      Neither of those produces the desired output for me. $x is never incremented. Since you require a space at the end of the string-to-be-substituted, there is no substitution after the last abc, and the desired spacing in the output is wrong:

      Those problems were present in the OP's posted code. They weren't problems with the post to which you replied. Presumably, the OP's code is different than what he posted, since the output he gave doesn't match the code he posted. Since the OP will have to retrofit the solution anyway, these details aren't important. That's why I took a few small liberties in my own solution.

        You are correct that there were problems in the OP's code. Since the OP also showed desired output, I was expecting that posted solutions would actually produce that output. Yours and dreadpiratepeter's solutions produced the desired output, but Jstrom's did not.

        Or perhaps I misunderstand.