CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Count number of occurrences in list

 



zapzap
User

Oct 16, 2013, 2:40 AM

Post #1 of 4 (1010 views)
Count number of occurrences in list Can't Post

Greetings,

I am trying to find the number of occurrences in a list. For example suppose we have:


Code
 
my @l = qw/a b c d e a b c c a b e/;

## I want to end up with a hash
my %hash

TIA


{ a => 3, b => 3, c => 3, d => 1 , e => 2 }


I was hoping to utilize either grep or map.


Zhris
Enthusiast

Oct 16, 2013, 6:29 AM

Post #2 of 4 (1007 views)
Re: [zapzap] Count number of occurrences in list [In reply to] Can't Post

Hi,


Code
my %hash; 

%hash = map { $_ => ++$hash{$_} } @l;
# or
grep { $hash{$_}++ } @l;
# or
$hash{$_}++ for (@l);


Chris


(This post was edited by Zhris on Oct 16, 2013, 8:46 AM)


Laurent_R
Veteran / Moderator

Oct 16, 2013, 2:22 PM

Post #3 of 4 (984 views)
Re: [Zhris] Count number of occurrences in list [In reply to] Can't Post

I frankly would use the first or third of the solutions proposed by Chris, but would tend to avoid the grep version because, although it works perfectly, it is using the grep function for something that it is not really designed to do and is therefore a bit more complicated to understand.

And if you want to print the resulting hash in the way described in the OP, you might do something like this:


Code
 print "{", (join ",", map {" $_ => $hash{$_}"} sort keys %hash), " }";


which should happily print:

Code
{ a => 3, b => 3, c => 3, d => 1, e => 2 }



zapzap
User

Oct 17, 2013, 12:15 AM

Post #4 of 4 (978 views)
Re: [Zhris] Count number of occurrences in list [In reply to] Can't Post

Thanx, good stuff.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives