in reply to Re: num keys of the hash within hash?
in thread num keys of the hash within hash?
... since the leading number is exactly what you want, the numification is actually successful ...However, the leading number may not be quite what is wanted.
Consider the following example:
In the both cases, the evaluation of scalar keys %{ $hash{one} } (or of keys %{ $hash{one} in a scalar context) is (and always will be) the same: 2.>perl -wMstrict -le "my %hash = ( one => { fee => 33, fie => 44, }, two => { foo => 2, bar => 3, baz => 4, }, ); my $k_n = keys %{ $hash{one} }; my $k_s = '' . %{ $hash{one} }; print $k_n; print $k_s, ' <--'; print scalar keys %{ $hash{two} }; print '' . %{ $hash{two} }; " 2 1/8 <-- 3 3/8 >perl -wMstrict -le "my %hash = ( one => { fee => 33, xyz => 44, }, two => { foo => 2, bar => 3, baz => 4, }, ); my $k_n = keys %{ $hash{one} }; my $k_s = '' . %{ $hash{one} }; print $k_n; print $k_s, ' <--'; print scalar keys %{ $hash{two} }; print '' . %{ $hash{two} }; " 2 2/8 <-- 3 3/8
However, the first digit of the stringization of '' . %{ $hash{one} } is not the same in both cases. There has been an unfortunate collision in one => { fee => 33, fie => 44 } and both 'fee' and 'fie' occupy the same bucket of the 8 allocated for this (anonymous) (sub-)hash. With one => { fee => 33, xyz => 44 }, this tragedy has been avoided and the two keys occupy two separate buckets.
Moral: As recommended by kennethk, always use the scalar evaluation of keys, not the stringization of the hash which, while interesting, may be misleading. And please don't suppress warnings without good reason.
Update: Here's a much more concise example. The details of the discussion above don't quite apply any more, but you get the picture.
>perl -wMstrict -le "my %ha = ( fee => 33, fie => 44, ); my %hb = ( fee => 33, xyz => 44, ); printf qq{keys (%s): %ld %s \n}, join(' ', sort keys %$_), scalar keys %$_, 'buckets used/allocated: ' . %$_, for \(%ha, %hb); " keys (fee fie): 2 buckets used/allocated: 1/8 keys (fee xyz): 2 buckets used/allocated: 2/8
|
|---|