Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Counting Substrings in Strings

by CmdrTaco (Initiate)
on Oct 27, 1999 at 04:27 UTC ( #858=perlquestion: print w/ replies, xml ) Need Help??
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).

Comment on Counting Substrings in Strings
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.
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.

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://858]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2014-09-19 14:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (140 votes), past polls