What is autovivification?

Autovivification is both a wonderful blessing and a curse in Perl. It eliminates a lot of
code required when initializing deep data structures, but if you come from a very
strict world it can freak you out at first.

Or make you wonder how could you live without it.

The word autovivification itself comes from the word vivify
which means to bring to life.

The simple cases for hashes

The most simple form of it is when you have a hash and you set a value of a
key that did not exist before.

Perl treats the not-existent value as undef.
When undef is used in a numerical operation it acts as if it was 0.
In most cases this would generate a use of uninitialized value" warning,
but specifically in the auto-increment operation it works without complaining.

The resulting value is then assigned back to the hash, creating the key.

The simple cases for arrays

In case of an array, if you assign a value to a not-existing element of the array,
or use auto-increment on such element, Perl will automatically enlarge the array
creating all the elements up to the required index, and assigning undef
to each intermediate element.

This means writing $counter[1_000_000]++; will enlarge the array to have a million elements almost all of them being undef.
Such a sparse array is a huge waste of memory.
In such cases a hash would be probably a better data structure to use.

Complex data structures

Autovivification starts to be really interesting on deep data structures. Even when creating a two dimensional hash,
you can just write $people{Foo}{phone} = '123-456'; and Perl will create the internal hash for the 'Foo' key:

In this case we don't assign any value to the hash, we just check if one of the
internal values (the phone of Foo) exists. It does not exist (Foo has not phone),
but the internal hash was created by this operation:

$VAR1 = {};
Foo has no phone
$VAR1 = {
'Foo' => {}
};

This is quite unfortunate.

This means we have changed the state of the %people has just by
observing it.

autovification and deleting elements

It looks even worse if we are trying to delete an element that does not exist:

In an attempt to reach the element that needs to be deleted, Perl
created the internal hash of 'Foo'.

A bug

I think these undesirable cases are now generally considered to be a bug in Perl.
Unfortunately it is very unlikely that this bug will be fixed in Perl 5 as there is a lot of code
out in the wild (both on CPAN and in companies) that rely on this behavior.
Correcting the behavior would break a lot of code.