Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Count number of occurrences of a substr

by aaron_baugher (Curate)
on Sep 28, 2011 at 19:10 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-19 04:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found