How do I disable autovivification in Perl?

Relatively new is the autovivification module, which lets you do this:

no autovivification;

Pretty straightforward.


You might want to use an object instead of the hash (see Moose) or use a strict tied hash. Or you can turn warnings into errors, if you really want to:

use warnings NONFATAL => 'all', FATAL => 'uninitialized';

You can lock the hash using one of the functions from Hash::Util (a core module).

use Hash::Util qw( lock_keys unlock_keys );

my $some_ref = { akey => { deeper => 1 } };
lock_keys %$some_ref;

print "too deep" if $some_ref->{deep}{shit} == 1;

Now the last statement will throw an exception:

Attempt to access disallowed key 'deep' in a restricted hash

The downside is, of course, that you'll have to be very careful when checking for keys in the hash to avoid exceptions, i.e. use a lof of "if exists ..." to check for keys before you access them.

If you need to add keys to the hash again later you can unlock it:

unlock_keys %$some_ref;
$some_ref->{foo} = 'bar'; # no exception