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