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";

In reply to Re^2: Progressive matching w/substitutions by broomduster
in thread Progressive matching w/substitutions by argv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.