Home > Articles > Web Development > Perl

📄 Contents

  1. References and Autovivification
  2. Autovivification and Lists
  3. Autovivification and Deeply Nested References
  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Autovivification and Deeply Nested References

One of the primary uses of autovivification is to assign lower-level data before the higher-level data exists. The following code snippet demonstrates this:

    01: my $deep_ref = {};
    02: $deep_ref->{Family}{Pets}[1]{cat} = "Tigger";
    03: $deep_ref->{Family}{Pets}[2]{dog} = "Zeke";
    04: $deep_ref->{Family}{Pets}[3]{fish}[0] = "Oscar";
    05: $deep_ref->{Family}{Pets}[3]{fish}[1] = "Jack";
    06: print qq{My cat is named $deep_ref->{Family}{Pets}[1]{cat}\n};
    07: print qq{My fish are named: } .
        join " and ", @{$deep_ref->{Family}{Pets}[3]{fish}};

Before assigning the value Tigger, none of the higher-level data structures even existed yet. But, by doing so, two other structures were autovivified; the Family hash reference and the Pets array reference. This can be extremely useful when you don't want to loop through your reference to see if an item exists, and if not, create it. As well, it allows you to create many structures within one reference at one time.

When you assign to an array reference, you may assign to elements before previous ones exist. For example, Tigger was assigned to the cats hash reference as the first index of the Pets array reference in line 2. This skipped the index of 0, so it was autovivified with the value of undef.

Figure 1 is a graphical representation of the $deef_ref hash reference that illustrates what has been created.

Figure Figure 1 Autovivification illustrated.

That's all there is to autovivification. It is an easy, but powerful tool to use when it is convenient. Until next time, enjoy!

  • + Share This
  • 🔖 Save To Your Account