is it a bug or feature?
Neither. It looks like undefined behavior to me. (Not joking.)
My response to "What do you think this would print?" was "Either 0 or 1, depending on subtle evaluation order concerns that are likely to change for 1) rather arbitrary reasons of implementation details and/or 2) as a result of optimizations". Either result is acceptable. That's why you shouldn't write code like that.
Basically, accessing $a{0} on the right hand side of your assignment creates the key
Actually, that can't be a valid explanation. The right-hand side instance of $a{0} is not in a "lvalue context"; that is, it is simply being read, not (potentially) being written to. So the (implicit or imagined) right-hand side instance of $a{0} does not trigger autovification.
It is the $a{0} on the left-hand side of the assignment that triggers vivification (not necessarily autovivification). It is just an implementation detail as to whether the slot for storing the value is created before or after keys %a gets evaluated.
Since Anonymous Monk shows that the answer is different (at least for some versions of Perl) in the case of the explicit version of "the same thing",
$a{0}= $a{0} || scalar keys %a;
I suspect that this really is the result of an optimization. ||= knows that it needs to both read from and write to the item on the left-hand side. So it just grabs a can-be-written-to instance of the left-hand side up front, which means the key slot gets allocated before the (implicit) || gets executed.
In $a{0}= $a{1} || scalar keys %a;, the $a{1} must be read before the || can decide whether or not to evaluate scalar keys %a. That does not autovivify $a{1}. The $a{0} has to be vivified and it is an implementation detail as to whether this is done before or after the other things to be done. It appears that at least some implementations of Perl vivify $a{0} after the right-hand side value has been computed.
- tye
In reply to Re^2: Without trying; what do you think this would print? (/left/ side)
by tye
in thread Without trying; what do you think this would print?
by lkundrak
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |