问题
I am doing the following, but it is not working properly:
my $enabled = $hash &&
$hash->{'key'} &&
$hash->{'key'}->{'enabled'} &&
$hash->{'key'}->{'active'};
Is this an acceptable way to assign a boolean value to a scalar variable? My code is misbehaving in strange ways, as it is, and I believe it is because of this assignment. I have validated that the individual values exist for all of these keys and are set to a value.
P.S. Sorry for being a noob! I googled for ~10 minutes and couldn't find the answer anywhere.
回答1:
The Perl boolean operators like &&
, ||
, and
, or
don't return a boolean value, they return the value of one of their arguments:
say 2 && 3;
outputs 3
.
You can force it to a boolean with the double negation trick:
say !!(2 && 3);
# or
say not not 2 && 3;
outputs 1
.
来源:https://stackoverflow.com/questions/17329142/how-can-i-assign-a-boolean-condition-result-to-a-scalar-variable-in-perl