Main Content

Autovivification - the magic appearance of variables in Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-01-21 08:16:09 - Graham Ellis

Here's a one line perl program that does nothing but set up a variable ... except that it does a lot!

$p[7]{john}{paul}[9] = 1;
 
__END__
 
A list called @p. Elements 0 to 6 are null, and element 7
is a reference to a hash ...
 
That hash contains a single member, key is "john" and the
values it holds is a reference to another hash ...
 
THAT hash contains a single member with a key of "paul" and
it contains a reference to a list ...
 
And that list has elements 0 to 8 being null, and element
nine containing the value 1.
 
AND THAT WAS ALL DONE AUTOMATICALLY by Perl's Autovivification
capability!!


If you assign to a variable in Perl and it does not already exist, the Perl creates it dynamically - and that implies that it also creates all the other necessary structures as well. My oneliner above took 10 lines to describe in plain English!

This is both powerful and dangerous. Something as simple as

$phone[1225708225] = 1;

will give you "out of memory" as a list of over one billion elements is calledup. But do remember that

$phone{1225708225} = 1;

will create a hash with just one member, and THAT is what you should use for data with sparsely distributed numeric keys