Autovivification is a default and standard behavior with Perl. Here is a simple, contrived example:
perl -MData::Dumper -e 'my %h; print "yes\n" if exists $h{d}{j}; print + Dumper \%h;' $VAR1 = { 'd' => {} };
What just happened here?
So when we're done, we have an anonymous hash stored in an element that never even existed before we asked. The best way to prevent this is to break your test into smaller chunks:
if(defined $h{d} && exists $h{d}{j}) {...}
If $h{d} is empty or non-existent then the Boolean of defined($h{d}) is false. The logical short circuit && operator stops dead in its tracks when the left-hand argument is false. This has the desirable effect of never getting to the code that tests for the existence of j if the test on the lefthand side of the && operator already returned false. Thus, we never force Perl to put a hashref where nothing existed before.
Autovivification is useful because it allows one to do this:
my %hash; $hash{d}{j} = 'foo';
Even though d never existed before, the fact that we are treating it as a reference to an anonymous hash, Perl is willing to oblige. It allows us to avoid doing this:
my %hash; $hash{d} ||= {}; $hash{d}{j} = 'foo';
You could look at it another way. Have you ever tried creating a path ~/foo/bar/baz? First you try mkdir foo/bar/baz, and you see "mkdir: cannot create directory 'foo/bar/baz': No such file or directory. So then you man mkdir and remember the -p flag. -p is autovivification for file paths. mkdir -p foo/bar/baz works similar to $hash{foo}{bar}{baz} = '...'.
By setting no autovivification; you are preventing Perl from being itself. That's fine, I suppose, until the next time you actually want autovivification, or the next time you forget to include that boilerplate at the top of the lexical scope where you need it. It's probably safer to just keep track of what can trigger autovivification.
Dave
In reply to Re: Strange Hash related bug, keys are created by themselves!
by davido
in thread Strange Hash related bug, keys are created by themselves!
by mak007
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |