You're partly correct. In the case of this example, where there is only a single level hash, exists will not autovivify the key. However, if this was a complex data structure containing a HoH, HoA, AoH, etc, then the intermediate references (but not the terminal reference) would be autovivified*. To avoid autovivifying the intermediate structures you have to use exists to check each one as you go, or use something like tye's Data::Diver. See the example below.
Output:use strict; use warnings; use Data::Diver qw( Dive ); use Data::Dumper; my %h; # The exists function will autovivify intermediate keys print "Testing with exists\n"; printf "key1 %s exist\n", exists $h{key1} ? 'does' : 'does not'; printf "key1-key2 %s exist\n", exists $h{key1}{key2} ? 'does' : 'does +not'; printf "key1 %s exist\n", exists $h{key1} ? 'does' : 'does not'; print Dumper( \%h ); # Data::Diver's Dive will not autovivify intermediate keys print "\nTesting with Data::Diver\n"; my @values = Dive ( \%h, 'key3', 'key4' ); printf "key3-key4 %s exist\n", @values ? 'does' : 'does not'; print Dumper( \%h );
Testing with exists key1 does not exist key1-key2 does not exist key1 does exist $VAR1 = { 'key1' => {} }; Testing with Data::Diver key3-key4 does not exist $VAR1 = { 'key1' => {} };
*You may know this, but someone else reading your reply may not realize the difference in behavior for single level vs multi level structures.
In reply to Re^3: What protects me from doing this stupid thing..? (autovivification)
by bobf
in thread What protects me from doing this stupid thing..?
by Cody Pendant
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |