in reply to No autovivification, for loop aliasing, lvalue vs rvalue in for loops

I have filed a bug: https://rt.perl.org/Ticket/Display.html?id=129177

Minimal code for reproduce is:

##### use Data::Dumper;$Data::Dumper::Indent=0; my $n = {}; for (@{$n->{'x'}}) { print 1; } print Dumper ($n), "\n"; ##### Output: ##### $VAR1 = {'x' => []}; ##### # the same throws exception: # Can't use an undefined value as an ARRAY reference @{$$n{'y'}} and print 2;

Explanation is (these are citations of perl gurus) :

The documentation of autovivification in the core distribution is clearly less than satisfactory. By consulting four different doc files (as well as the CPAN autovivification documentation), have pieced together the following explanation which should be treated as a *provisional, layperson's* explanation of the phenomenon. The documentation is somewhat adequate in explaining why array and hash elements autovivify when they do, but -- as you have probably found out already -- quite inadequate in explaining why autovivification does *not* happen where you might expect it to.
So here goes.
Perl autovivifies intermediate elements in data structures when it senses that you need to use the lowest elements in such structures as *storage locations*. In Perl, a storage location is referred to as an *lvalue* (where the 'l' refers to the customary 'left-hand side' or an assignment). The context in which you are assigning a value to a storage location -- or when Perl senses that you are about to assign a value to a storage location -- is referred to as *lvalue context*. When you need to assign a value to an array or hash element that doesn't already exist, Perl will create that elements -- and any elements needed to reach that element -- for you. More formally, when you are in lvalue context, perl will autovivify data structures as needed.

The possibility of making foreach refrain from autovivification when possible has been raised before (i.e., it would be considered a bug fix), but it has been put off indefinitely because it would cause a significant slowdown.

  • Comment on Re: No autovivification, for loop aliasing, lvalue vs rvalue in for loops
  • Download Code