CmdrTaco has asked for the wisdom of the Perl Monks concerning the following question:
Whats a clean way to count the occurances of a substring
withing a string? I've been using $x++ while /foo/g; to count the
occurances of 'foo' within $_, but it really seems like $x=/foo/g;
ought to (in scaler context) return a count, but for some reason it
always returns either undef or 1 (eg, a boolean).
Try the Substitution Operator
by chromatic (Archbishop) on Dec 24, 1999 at 12:02 UTC
|
my $count = ($string =~ s/(foo)/$1/g); will also do the trick. Benchmarking is left as an exercise for the discerning acolyte.
The match operator (/foo/) only returns a boolean to indicate that it did or did not match. Our friend Mr. Substitution gives us more data.
tr/// is probably much faster for simple substrings, not regex's. | [reply] |
Re: Counting Substrings in Strings
by pschoonveld (Pilgrim) on Dec 02, 1999 at 12:03 UTC
|
$count = $string =~ tr/x/x/;
Will make $count = num of x's in $string. | [reply] |
Re: Counting Substrings in Strings
by audreyt (Hermit) on Aug 05, 2002 at 22:51 UTC
|
Please use a list context switcher. :)
$text = 'asdasd';
$count = () = $text =~ /asd/g;
| [reply] [d/l] |
|