in reply to Counting hash of hashes elements
#!/usr/bin/perl -w use strict; use warnings; my %hash = ( 'a' => { 'x' => 40, 'z' => 102 }, 'b' => { 'z' => 100, 'x' => 10, 'y' => 20 }, 'c' => { 'x' => 50 }, 'd' => { 'z' => 101, 'y' => 30 } ); sub stats { my ($hhp, $SearchKey, $SearchVal) = @_; my %counters; # a counter hash of which keys are used at level two my $SearchCount; foreach my $key1 (keys %$hhp) { my @cList = keys %{$hhp->{$key1}}; ++$counters{join('+',sort @cList)}; ++$SearchCount if exists $hhp->{$key1}->{$SearchKey} and $hhp->{$key1}->{$SearchKey} == $SearchVal +; } return $SearchCount, %counters; } #### main my ($SearchCount, %result) = stats(\%hash,'z',101); foreach my $key (sort keys %result){ print "$key \t$result{$key}\n"; } print "Count of z==101 is $SearchCount\n"; __END__ ## OUTPUT ## x 1 x+y+z 1 x+z 1 y+z 1 Count of z==101 is 1
Earth first! (We'll rob the other planets later)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Counting hash of hashes elements
by perlcapt (Pilgrim) on Nov 02, 2004 at 00:56 UTC |