perlautovivification

Analysis of a Perl autovivification example


Consider this one piece of Perl code,

$array[$x]->{“foo”}->[0] = “January”;

I analyze this code as following: The entry with index $x in the @array is a hashref. With respect to this hash, when its key is foo, its value is an array and the 0-th element for this array is January. Is my analysis correct or not?


Solution

  • Your analysis of the structure is correct, however the related autovivification example would be something more like:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use 5.10.0; # say
    
    my @array;
    
    # check all levels are undef in structure
    
    say defined $array[0] ? 'yes' : 'no';         # no
    say defined $array[0]{foo} ? 'yes' : 'no';    # no
    say defined $array[0]{foo}[0] ? 'yes' : 'no'; # no
    
    # then check again
    
    say defined $array[0] ? 'yes' : 'no';         # yes (!)
    say defined $array[0]{foo} ? 'yes' : 'no';    # yes (!)
    say defined $array[0]{foo}[0] ? 'yes' : 'no'; # no
    

    Notice that you haven't assigned anything, in fact all you have done is to check whether something exists. Autovivification happens when you check a multilevel data structure at some level x, then suddenly all levels lower (x-1 ... 0) are suddenly existent.

    This means that

    say defined $array[0]{foo}[0] ? 'yes' : 'no';
    

    is effectively equivalent to

    $array[0] = {};
    $array[0]{foo} = [];
    say defined $array[0]{foo}[0] ? 'yes' : 'no';