in reply to (tye)Re: how to get the number of times a pattern matched
in thread how to get the number of times a pattern matched
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;
|
|---|