The following snippet is not working as expected:
$k{"foo"}=1;
$k{"bar"}=2;
if(not defined($k{"foo"}) && not defined($k{"bar"})){
print "Not defined\n";
}
else{
print "Defined"
}
Since both $k{"foo"} and $k{"bar"} are defined, the expected output is "Defined". Running the code, however, returns "Not defined".
Now, playing around with the code I realized that placing parentheses around each of the not defined()
calls produces the desired result:
if((not defined($k{"foo"})) && (not defined($k{"bar"}))){print "Not Defined"}
I imagine this has something to do with operator precedence but could someone explain what exactly is going on?
Precedence problem.
not defined($k{"foo"}) && not defined($k{"bar"})
means
not ( defined($k{"foo"}) && not defined($k{"bar"}) )
which is equilvalent to
!defined($k{"foo"}) || defined($k{"bar"})
when you actually want
!defined($k{"foo"}) && !defined($k{"bar"})
Solutions:
!defined($k{"foo"}) && !defined($k{"bar"})
not defined($k{"foo"}) and not defined($k{"bar"})
(not defined($k{"foo"})) && (not defined($k{"bar"}))
PS - The language is named "Perl", not "PERL".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With