Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

RE: Counting occurances

by dempa (Friar)
on Jul 13, 2000 at 17:12 UTC ( [id://22369]=note: print w/replies, xml ) Need Help??


in reply to Counting occurances

I've been thinking 'bout this for a while now, and I cannot come up with anything better. I'm sure someone else can tho'. Anyway, if you just wanted to know the number of occuranes for one element, you could use:
@a=('a', 'b', 'a', 'a'); print "a occurs " . scalar grep(/a/,@a) . " times\n";

Replies are listed 'Best First'.
RE: RE: Counting occurances
by merlyn (Sage) on Jul 13, 2000 at 17:50 UTC
    Don't use a regex if you don't really want a regex, which you don't, because you now found all the items that contain "a", not just be equal to them. You probably wanted this instead:
    print "a occurs ".grep($_ eq "a", @list)," times\n";

    -- Randal L. Schwartz, Perl hacker

      OK, my point was to show that grep returned the number of occurances in scalar context, but ofcourse you're right. Point taken.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-23 21:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found