in reply to Strange behaviour of interpreter when dereferencing an undefined value

References in lvalue context autovivify.

%{ $a } in lvalue context is effectively %{ $a //= {} }

@{ $a } in lvalue context is effectively @{ $a //= [] }

For example,

>perl -MData::Dumper -E"my $ref; $ref->{a}{b} = 'c'; print Dumper $x;" $VAR1 = { 'a' => { 'b' => 'c' } };

As you can see, $x->{a}{b} in lvalue context is effectively ( ( $x //= {} )->{a} //= {} )->{b}.

You can control the behaviour using the autovivification module. (Don't file a bug report.)

Replies are listed 'Best First'.
Re^2: Strange behaviour of interpreter when dereferencing an undefined value
by kejv2 (Acolyte) on Nov 03, 2014 at 20:43 UTC
    I can't see how this could be related to my examples since in
    perl -we'use strict; sub foo {}; my $a; foo( %{ $a } )'
    the expression %{ $a } isn't in lvalue context. Also autovivification doesn't appear only in lvalue context:
    perl -MData::Dumper -we'use strict; my $a; $a->{b}{c}; print Dumper $a +' $VAR1 = { 'b' => {} };

      the expression %{ $a } isn't in lvalue context.

      Yes, it is.

      $ perl -E'sub f { $_[0] = 'abc' } f($x); say $x' abc $ perl -E'sub f { $_[1] = 'abc' } $h{a}=undef; f(%h); say $h{a}' abc

      Perl arguments are always passed by reference.

      Also autovivification doesn't appear only in lvalue context

      I didn't say otherwise.