Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Count number of occurrences of a substr

by aaron_baugher (Curate)
on Sep 28, 2011 at 19:10 UTC ( #928392=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2021-12-06 18:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (33 votes). Check out past polls.

    Notices?