Search code examples
perlautovivification

Perl auto-vivification on assignment


Does Perl real auto-vivifies key when the unexisting key is assigned to a variable?

I have this code :

my $variable = $self->{database}->{'my_key'}[0];

The variable $self->{database}->{'my_key'}[0] is undefined in my hash, but if I print a Dumper after the assignment, I'm surprised that the my_key is created.

I know the functionality for this case :

use Data::Dumper;

my $array;

$array->[3] = 'Buster';  # autovivification
print Dumper( $array );

This will give me the results :

$VAR1 = [ undef, undef, undef, 'Buster' ];

But never expected to work the other way arround, where : my $weird_autovivification = $array->[3]; will also vivify $array->[3].


Solution

  • Does Perl real auto-vivifies key when the unexisting key is assigned to a variable?

    Perl autovivifies variables (including array elements and hash values) when they are dereferenced.

    $foo->{bar}   [ $foo dereferenced as a hash   ]    ≡    ( $foo //= {} )->{bar}
    $foo->[3]     [ $foo dereferenced as an array ]    ≡    ( $foo //= [] )->[3]
    $$foo         [ $foo dereferenced as a scalar ]    ≡    ${ $foo //= do { my \$anon } }
    etc
    

    This means that

    $self->{database}->{'my_key'}[0]
    

    autovivifies

    • $self (to a hash ref if undefined)
    • $self->{database} (to a hash ref if undefined)
    • $self->{database}->{'my_key'} (to an array ref if undefined)

    but not

    • $self->{database}->{'my_key'}[0] (since it wasn't dereferenced)

    But never expected to work the other way arround, where : my $weird_autovivification = $array->[3]; will also vivify $array->[3].

    Not quite. It autovivifies $array, the variable being dereferenced. Nothing was assigned to $array->[3] since it wasn't dereferenced.


    Tip: The autovivification pragma can be used to control when autovivification occurs.