Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Find number of unique values in hash

by jethro (Monsignor)
on Jan 19, 2010 at 22:11 UTC ( [id://818308]=note: print w/replies, xml ) Need Help??


in reply to Find number of unique values in hash

I don't see a faster way for this. But if you need to count often, you could generate a second HoH for a one-time cost and have that and all other counts for no cost at all after that.

my %counts=(); foreach $kid (%hoh) { foreach my $attribute (%$kid) { $counts{$attribute}{$kid->{attribute})++; } } ... print $counts{'age'}{12};

Sadly this "one-time" cost has to be paid whenever the data changes (unless you also adjust the counts in the second HoH whenever you change anything)

UPDATE: Fixed the bug in the first line thanks to warnings from johngg and chromatic. It was too much to hope that I could write even a 4-liner without a trivial bug.

Replies are listed 'Best First'.
Re^2: Find number of unique values in hash
by johngg (Canon) on Jan 20, 2010 at 00:04 UTC
    my %counts={};

    I think you need parentheses rather than curlies there. As it is, you are assigning a single hash reference to the hash, which it will then stringify and use as a key with no corresponding value. Also, if you use warnings;, I think you will get one complaining about odd number of elements in hash assignment, or words to that effect. Trying it I get this.

    $ perl -MData::Dumper -Mstrict -wle ' > my %h = {};' > print Data::Dumper->Dump( [ \ %h ], [ qw{ *h } ] );' Reference found where even-sized list expected at -e line 2. %h = ( 'HASH(0x817f880)' => undef ); $

    I hope this is useful.

    Cheers,

    JohnGG

Log In?
Username:
Password:

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

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

    No recent polls found