http://qs321.pair.com?node_id=928392


in reply to Count number of occurrences of a substr

That page you referenced isn't quite right. The m// operator never returns the number of matches. In scalar context, it returns true (1) if the match succeeds or false if it doesn't. In list context, it returns a list of matches, which you can turn into a count by passing it through an anonymous list:

#!/usr/bin/perl use Modern::Perl; my $str = 'thisthis'; my $n = $str =~ /this/g; say $n; $n = $str =~ /that/g; say $n; ($n) = $str =~ /this/g; say $n; $n = () = $str =~ /this/g; say $n; #output 1 this 2

The s/// operator, on the other hand, does return the number of matches, regardless of whether it's called in scalar or list context.

Replies are listed 'Best First'.
Re^2: Count number of occurrences of a substr
by FunkyMonk (Chancellor) on Sep 30, 2011 at 22:18 UTC