Should the following two lines of code do the same thing?
$hash{$_} ||= 1 + keys %hash for @list;
$hash{$_} = $hash{$_} || 1 + keys %hash for @list;
IMO the second one should be well defined. [tye] and [diotalevi] think that both are undefined, I could be conviced about the first, but I need more convincing on the second.
$hash{foo} ||= keys %hash;
for($hash{foo}) { $_ ||= keys %hash; }
At least, the results agree: the hash element exists (hence, it is counted in [keys]), before the assignment is called. My rule of thumb is: if you use a hash element as a R/W L-value, then it'll autovivify. It'll even autovivify in the for loop, if the loop body is empty:
for($hash{foo}) { } # results in { 'foo' => undef }
I was surprised to see an exception when using a hash element as a sub parameter:
sub blackbox { ... }
blackbox($hash{foo});
may or may not autovivify $hash{foo}, depending on what blackbox() does. For example:
sub blackbox { } # no autovivify
sub blackbox { $_[0] = 123 } # results in { 'foo' => 123 }
Tested with perl 5.8.7
$hash{$_} ||= 1 + keys %hash for @list;
$hash{$_} = $hash{$_} || 1 + keys %hash for @list;
Hmmm. I thought it was a precedence issue. Expanding slightly:
for ( @list ) {
$hash{$_} ||= ( 1 + keys %hash );
}
for ( @list ) {
$hash{$_} = ( $hash{$_} || ( 1 + keys %hash ) );
}
I get why the second one works -- the (1 + keys %hash) evaluates first due to precedence, resulting at first in 1 + 0 = 1. Etc.
But I'm surprised at the first one, given the low precedence of assignment. It seems as if the shortcut check is happening first (with higher precedence), to see if the rest of the expression is even worth evaluating and thus autovivifying before the addition happens. (An optimization bug?)
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
$hash{foo} ||= exists $hash{foo};
versus
$hash{foo} = $hash{foo} || exists $hash{foo};
perlmonks.org content © perlmonks.org and bart, demerphq, whio, xdg, zshzn
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03