Last time I spoke about wrapping hash access I got a bit more than I bargained for. It’s still something I’m tempted to do from time to time.
Autovivification by default is very sensible (or perhaps Perl just suits me). When I set a parameter within a structure, I generally want all the ancestors to be created first. That’s why I have the following aliases to mkdir.
jared@localhost $ alias | grep mkdir alias failingmkdir='/bin/mkdir' alias mkdir='mkdir -p'
Autovivification on data retrieval though, can be a bit confusing.
use strict; my $data = {}; print '1:', exists($data->{'key1'}), "\n"; if (! exists($data->{'key1'}{'key2'})) { print '2:', exists($data->{'key1'}), "\n"; }
jared@localhost $ perl5.10 t.pl 1: 2:1
The CPAN Autovivification Module
Fortunately, it’s easy enough to disable it with the autovivification module.
no autovivification qw(strict fetch exists delete);
perl t.pl 1: Reference vivification forbidden at t.pl line 7.
Promote Uninitialized Warnings to Fatal
Zoul mentions a way to avoid typical autovivification errors1 on stackoverflow.
use warnings NONFATAL => 'all', FATAL => 'uninitialized';
Or unlock_keys and lock_keys_plus from Hash::Util mentioned by Chas. Owens in the comments might be closer to what is needed in some circumstances.
1. True, it doesn’t only apply to autovivification, but the other effects are useful too.
I don’t see where warnings.pm should affect autovivification in any way. Put the warnings line on top of your example, run it again, same output.
Install autovivification (the module) from CPAN to really disable autovivification.
Hi Henning,
Oops! Egg on my face a bit there, not testing before posting. But at least I know a few people are reading what I’m writing
I’ll correct this.