Perl's "not" operator not working as expected with the defined() function
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?
Answers
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".