in reply to Counting multiple matches of RegExp in single line

And here's another way to do it (probably clearer):

$count++ while $teststring =~ /test/g;

Note that there's no need for parens this time.

Replies are listed 'Best First'.
Re^2: Counting multiple matches of RegExp in single line
by bart (Canon) on Nov 27, 2004 at 13:06 UTC
    If you mean the parens in the regex, you don't need them using the other way, either. /PAT/g in list context, will imply parens around the whole match, if none are provided in the pattern.
    $count = () = $teststring =~ /test/g;
    will just work fine.

    This is documented in perlop, see the last sentence in this paragraph:

    The "/g" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.
      Hey, good stuff, thanks for the tip.