SPUG: Slice of HashOfHash

David Dyck david.dyck at fluke.com
Wed Nov 15 21:51:58 PST 2006

Not sure if your advice is cargo-cult, please test it.

On Wed, 15 Nov 2006 at 16:32 -0800, jerry gay <jerry.gay at gmail.com> wrote:

>> for my $key ( qw[ flintstones jetsons jones simpsons ] ) {
>>     if ( $HoH{ $key }{ husband } eq 'fred' ) {
> probably better not to hardcode here:
>  for my $hash ( @HoH{ keys %HoH } ) {
>      if ( $hash->{ husband } eq 'fred' ) {

you were right to warn about not hardcoding the keys above
as if there is a typo in the above keys (eg s/jones/smith/) then
a top level element would be autovivified (eg  $HoH{'smith'} = undef)
but I suspect that the following advice is wrong:

> but the if statement is somewhat unsafe. in the case where the subhash
> doesn't have a key named 'husband', it will be autovivified. this may
> or may not be a problem.

The above _may_ have been true at some version of perl (as I used to
write code like below also (using exists) - but it is not now the case when
I test the code.  I you find a perl doing this (where
   if ( $hash->{ exhusband } eq 'fred' ) 
autovivifies some element in %HoH), please let me know, as I couldn't
create a test case with recent (6 year old) perl version where the
if test needed the exists check that you gave below.

> if it is, you'll want something more like:
>  for my $hash ( @HoH{ keys %HoH } ) {
>      if ( exists $hash->{ husband } and $hash->{ husband } eq 'fred' ) {

More information about the spug-list mailing list