Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Count of occurences

by borisz (Canon)
on Jun 13, 2006 at 10:11 UTC ( [id://554987]=note: print w/replies, xml ) Need Help??


in reply to Count of occurences

Here is one way:
$_ = 'hi there hi there'; my $n = () = /here/g; print $n;
Boris

Replies are listed 'Best First'.
Re^2: Count of occurences
by kwaping (Priest) on Jun 13, 2006 at 15:49 UTC
    That works and is probably the best solution. Since I get the feeling the OP might be new to Perl, I'm going to explain the above code.

    First, the special variable $_ is set to the string to be matched against. On the next line, many things happen. First, there is a pattern match performed by //, which operates on the $_ variable by default. The g modifier to this operation makes it find all matches of the pattern "here", instead of the default action which is to find just the first match. The result of this operation is returned as a list, which is temporarily stored in (). This anonymous array is then evaluated in a scalar context by assigning it to the lexically-scoped variable $my. Evaluating an array in a scalar context returns the number of elements in the array. Since this array consists of all the matches of the string "here" inside the value of $_, you end up with $n being the count of occurences, which is what you were seeking.

    ---
    It's all fine and dandy until someone has to look at the code.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-26 03:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found