SPUG: Slice of HashOfHash

DeRykus, Charles E charles.e.derykus at boeing.com
Thu Nov 16 10:29:55 PST 2006

>>> 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
>(eg  $HoH{'smith'} = undef) but I suspect that the following advice is

>> but the if statement is somewhat unsafe. in the case where the
>> 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.

Although not directly relevant here, there's an arrow operator
surprise mentioned in 'exists':

   undef $ref;
   if (exists $ref->{"Some key"})      { }
    print $ref;             # prints HASH(0x80d3d5c)

Although I couldn't conjure up an example, there might be a way to
get into trouble here if the top level HoH were a hash reference.

I recall a hideous bug where I had to adopt the exists doc workaround:

    if ( $ref                        and
         $ref->{$x}                  and
         $ref->{$x}{$y} ...

Charles DeRykus

More information about the spug-list mailing list