Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I'm wondering if it's possible to count the number of substitutions made by s///g? While one could count the matches by doing scalar(@array = m//g), I couldn't find an equivalent for the substitution operator. Is this possible, or do I have to make two runs through the string: one to count, one to substitute?

Replies are listed 'Best First'.
Re: Count substitutions by s///g
by sauoq (Abbot) on Jul 25, 2003 at 20:21 UTC
    my $num_substitutions = $var =~ s/foo/bar/g;

    Quoting from perldoc perlop:

    s/PATTERN/REPLACEMENT/egimosx Searches a string for a pattern, and if found, replaces + that pattern with the replacement text and returns the numbe +r of substitutions made. Otherwise it returns false (specif +ically, the empty string).

    -sauoq
    "My two cents aren't worth a dime.";
    
      Crap, I've been using it as: if (s///) {} thinking it was just returning success/failure. That was a stupid question: thanks.