http://qs321.pair.com?node_id=691609


in reply to Explaining Autovivication

When a scalar ($foo, $foo[$i], $foo{$k}) is undefined and it is used as a reference (@$foo, $foo->[$i], ${$foo}[$i], %$foo, $foo->{$k}, ${$foo}{$k}, $$foo), two things can happen.

One possibility is that you get a warning. This occurs when you are trying to read from the dereferenced structure. (Technically, when the reference is used as an rvalue).

>perl -wle"my @x = @$ref; print $ref" Use of uninitialized value in array dereference at -e line 1. Use of uninitialized value in print at -e line 1.

The other possibility is that the reference is autovivified. That means the appropriate structure (array, hash or scalar) is constructed and a reference to it is stored in the variable. This occurs when you are trying to write to the dereferenced structure. (Technically, when the reference is used as an lvalue).

>perl -wle"@$ref = my @x; print $ref" ARRAY(0x225228)

Note then creating an alias to the dereferenced structure is an lvalue, and results in autovivification.

>perl -wle"sub {}->(@$ref); print $ref" ARRAY(0x225230) >perl -wle"for (@$ref) {} print $ref" ARRAY(0x225228)