Home > Articles > Web Development > Perl

Perl and Autovivification

  • Print
  • + Share This
Perl programmers of the world, learn how to be even more lazy and let Perl do the work for you. Discover the power of autovivification and referencing the dereferenced.
From the author of

Three characteristics of programmers are laziness, impatience, and hubris. Using Perl allows a developer to be lazy. So, having any tool in your toolbox that allows you to be lazy is always welcome. Autovivification is one of those tools. You may have made it occur and not realized it, or you may have seen it, but didn't know what was happening. This article explains autovivification, and shows you how to use it to be lazy.

References and Autovivification

Assume that you need to create a reference that contains other references and data structures. However, you don't want to step through the creation of all the preceding data structures to put your final values in place. To do this, you can use something called autovivification.

Autovivification occurs when Perl automatically creates a reference when an undefined value is dereferenced. Perl will create the appropriate types of references, as determined by the way they are being referenced. Take the following code, for example:

    01: my $href = {};
    02: $href->{Fruit}->{Bananas}->{Yellow} = "In Season";
    03: print "Red Apples are not in season.\n"
        unless exists $href->{Fruit}->{Apples}->{Red};
    04: print $href->{Fruit}->{Apples}->{Red};
    05: print join "\n", keys %{$href->{Fruit}};

Line 2 is autovivification in action. Because the $href hash reference has no values at this time, line 2 is creating keys to satisfy the desired final key/value pair. Line 3 will print the string "Red Apples are not in season" if the $href->{Fruit}->{Apples}->{Red} key does not exist (which it does not, at this point).

When this code is run, the following is the output:

    Red Apples are not in season.
    Bananas
    Apples

Where did the Apples key in the Fruit hash reference come from? Perl created it for us when we attempted to access Red because it assumes that we want the Apples hash reference (since it was used in context as having some value). And, in turn, trying to access Apples created the Fruit key. By using this shortcut, programmers can avoid having to create the above data structure like the following:

    my $href = {};
    $href->{Fruit} = {};
    $href->{Fruit}->{Apples} = {};
    $href->{Fruit}->{Bananas}->{Yellow} = "";
    $href->{Fruit}->{Bananas}->{Yellow} = "In Season";
  • + Share This
  • 🔖 Save To Your Account