Consider the difference between:
1 while s/$string//;
and
s/$string//g;
when
$_ = "aaaaabbbbb"; $string = "ab";

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: 1 while s/// vs s///g
by gregor42 (Parson) on May 23, 2001 at 23:42 UTC

    Merlyn-sama,

    gregor42 bows humbly...

    Do I grok your intention or am I to go back to meditation? .. :

    1 while s/$string//;

    Will 'collapse' the string:

    "aaaaabbbbb"

    From the middle... As each centre pair of "ab" are 'removed'(replaced will nil) the regex starts over completely and repeats the process. An extra 'a' on the left or an extra 'b' on the right of that string would be left over at the end of the operation.

    INPUT: aaaaabbbbb OUTPUT:


    Whereas:

    s/$string//g;

    Though looking at the string repeatedly, it does it's matching against only the first string and not the string subsequent to substitution. Hence, only the centre pair are removed and the rest left over. The added 'a' or 'b' on the left & right respectively, if added singly or doubly would not change how often the pattern is matched & would still be present with the rest of the characters in the string.

    INPUT: aaaaabbbbb OUTPUT: aaaabbbb


    Most thought provoking.... Thank you once again for sharing with those of us with lesser brain.

    Was there deeper/more subtle meaning that I missed out on?



    Wait! This isn't a Parachute, this is a Backpack!
      Was there deeper/more subtle meaning that I missed out on?
      Go forth, my son, and share your newfound knowledge with friends and loved ones.

      -- Randal L. Schwartz, Perl hacker

      I had a strange vision of pumping lemmings when I read that...

      Seriously, the while loop is also different (doesn't matter here but does in more real code where a s//g is the condition of a while with a non-empty body) because without the /g modifier the pos will not be set and /G doesn't work.

      —John

Re (tilly) 1: 1 while s/// vs s///g
by tilly (Archbishop) on May 23, 2001 at 21:48 UTC
    Don't forget to consider the performance difference when:
    $_ = "abc" x 200_000; $string = "ab";
    UPDATE
    I started with 2 million, then changed to 200,000 because I thought that would be slow enough. But I messed up. Now fixed.
Re: 1 while s/// vs s///g
by dws (Chancellor) on May 24, 2001 at 05:19 UTC
    I first encountered this while looking for a quick way to "commify" a string.     1 while s/(\d)(\d\d\d)(?=$|\.|,)/$1,$2/; Works quite well for integers and currency, though it fails in a "D'oh!" way if you feed it a string that has more than three digits after a decimal point.