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.
means
which is equilvalent to
when you actually want
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”.