Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Find number of unique values in hash

by saberworks (Curate)
on Jan 19, 2010 at 22:04 UTC ( #818303=note: print w/ replies, xml ) Need Help??


in reply to Find number of unique values in hash

Here are two ways to do it.

use warnings; use strict; my %hoh = ( kevin => { age => "12", favorite_color => "blue", gender => "boy", }, john => { age => "11", favorite_color => "green", gender => "boy", }, lisa => { age => "11", favorite_color => "pink", gender => "girl", }, sara => { age => "13", favorite_color => "purple", gender => "girl", }, shelly => { age => "12", favorite_color => "purple", gender => "girl", }, ); my $num_12 = grep { $_ == 12 } map { $hoh{$_}->{'age'} } keys %hoh; my $num_alt = grep { $hoh{$_}->{'age'} == 12 } keys %hoh; print "Num 12: $num_12\n"; print "Num 12 alt: $num_alt\n";


Comment on Re: Find number of unique values in hash
Download Code
Re^2: Find number of unique values in hash
by CountZero (Bishop) on Jan 19, 2010 at 22:16 UTC
    Improving on your idea:
    print scalar grep{$_->{'age'} == 12} values %hoh;

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      I like yours better.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2014-08-30 08:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (291 votes), past polls