Today I was surprised when I came across the following behaviour in perl:
sub f { die if %{ $_[0] }; 42 }
my %h;
$h{x} ||= f(\%h); # we die. $_[0] references a hash with an 'x' key during f's run-time
In contrast, given the same set-up, the following statement behaves differently.
$h{x} = $h{x} || f(\%h); # $h{x} is now 42
Is this potential difference between assign-or and the combination of assignment and logical-or documented somewhere?
If this is due to auto-vivification, is it a bug or missing feature in the autovivification module which doesn't seem to be able to detect auto-vivification in this particular construct?
The critical bit is that merely checking on a key doesn't autovivify it
Prints nothing; key
khas not been added to the hash. (One needs more for autovivification to kick in, like to test nested keys -- then the ones leading up to the last one must be created.)This explains how the two cases differ: with
||=the$h{x}is being assigned to when the subfruns† and so keyxmust be first created for the purpose of that assignment, while in the other case$h{x}is only checked before the subfruns, so no autovivification happens.I don't know the actual implementation of
||=nor did I find any specific statement in the docs.† The
||=is listed as an assignment operator