Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Counting Substrings in Strings

by CmdrTaco (Their Supreme Effulgence)
on Oct 27, 1999 at 04:27 UTC ( [id://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).

Replies are listed 'Best First'.
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 pschoonveld (Pilgrim) on Dec 02, 1999 at 12:03 UTC
    $count = $string =~ tr/x/x/; Will make $count = num of x's in $string.
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
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://858]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-19 18:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found