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?)
I take that back. I'm forgetting the short-circuit. As I pondered this, the key isn't created in the hash until an assignment happens. Semantically, it looks like this is happening:
$hash{$_} ||= 1 + keys %hash;
# looks more like:
( $hash{$_} = $hash{$_} ) || ( $hash{$_} = 1 + keys %hash )
-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.
|