Perl's hash of hash of hash redeclaration? -


lets suppose have hash of hash of hash (%hash) values

warn dumper \%hash;      'key1'=> {'subkey1'} => {'subsubkey11'} => {'value1'}       'key2'=> {'subkey2'} => {'subsubkey22'} => {'value2'}      ... 

then, want verify if combination of keys absent (assume there above if loop on series of combinations $val1 , $val2 ).

if (!exists $hash{$val1}{$val2} ) {  #### verifying existent of key , subkey, not subsubkey      print "doesn't exists"; } 

if use after loop finish, going see this:

warn dumper\%hash;       'key1' => {'subkey1'} => {}      'key2' => {'subkey2'} => {} 

'key1' , 'subkey1' somehow been "assigned" void values and, because may loop several times on same combination of un-existent keys, after first loop on pair of keys second if takes combination existent.

what causes , best way solve it. tried dereferencing hash inside if , got error

    exists argument not hash or array element or subroutine  

this happens because treating $hash{$var1} hash reference automatically becomes one; called autovivification , can handy.

you can disable installing , using autovivification pragma:

if ( { no autovivification; ! exists $hash{$var1}{$var2} } ) { 

or can manually same thing do:

if ( ! exists ${ $hash{$var1} || {} }{$var2} ) { 

(here, if $hash{$var1} isn't set, don't use hash reference, use empty hash instead.)

or, if seems more readable you, can do:

if ( ! ( $hash{$var1} && exists $hash{$var1}{$var2} ) ) { 

Popular posts from this blog