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

does anyone know the easiest way to figure out how many times the last regex matched something?
  • Comment on how to get the number of times a pattern matched

Replies are listed 'Best First'.
Re: how to get the number of times a pattern matched
by MeowChow (Vicar) on Jun 02, 2001 at 00:58 UTC
(zdog) Re: how to get the number of times a pattern matched
by zdog (Priest) on Jun 02, 2001 at 00:43 UTC
    The pattern matching function m// should return the number of times the pattern matched.

    Update: Wups. My mistake. Nevermind.

    Update 2: However, s/// does what I thought m// does, so you can do something like:

    my $count = ($string =~ s/(pattern)/$1/g;)

    Good luck.

    Zenon Zabinski | zdog | zdog7@hotmail.com

Re: how to get the number of times a pattern matched
by Masem (Monsignor) on Jun 02, 2001 at 00:44 UTC
    The m// returns an array of the matches, so simply referencing that in scalar will give you the number of matches:
    my $text = "my dog is green"; my $count = ( $text =~ /g/g ); # $count is 2
    See perlre for more details.
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain

      Actually, no, that puts the match into a scalar context which means that it just returns a "true" or "false" value. However: my $count= ()= $text =~ /g/g; works since an array assignment returns the number of items in the right-hand value when used in a scalar context.

              - tye (but my friends call me "Tye")

        But getting the *number of matches* via that method will depend on the pattern itself --- in list context, the list of matches are returned, but if there are capturing parens the list of captured items are returned (which can be more than 1 per match):

        my $text = "my dog is green"; my $count =()= $text =~ /(g)(.)/g; print $count;

        That prints 4, although the pattern only matched twice. To get the number of matches you'll really need to count them:

        my $text = "my dog is green"; my $count; $count++ while $text =~ /(g)(.)/g; print $count;

        Or perhaps use the s/// operator (which returns the number of substitutions) and replace everything matched by itself if you don't want to change the string:

        my $text = "my dog is green"; my $count = $text =~ s/(g)(.)/$1$2/g; print $count;
      Not quite. Assigning to a scalar puts the regex into scalar context, which causes it to return a 1 if there's any matches, or 0 otherwise.

      You need:

      my $count = () = $text =~ /g/g;
         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print