Search code examples
perlautovivification

Why perl autovivification does not work for ->@* but ->@[0] does?


I may get values by slicing:

($x, $y, $z) =  $hash->{ key }->@[0,1,2]

Why I can not to write?

($x, $y, $z) =  $hash->{ key }->@*

For second expression in cases when key is not defined in hash I get error:

Can't use an undefined value as an ARRAY reference at ...


Solution

  • A slice gets you lvalues (writable scalars) for each index specified; a list context array dereference doesn't make any lvalues. And the general rule is that autovivification only applies with lvalues.

    For example ->@* will autovivify in this case:

    push $hash->{ key }->@*, 1;