The Perl "not" operator does not work properly with a specific () function

The following snippet does not work properly:

$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 result is determined to be "Defined". However, running the code returns "Undefined".

Now, playing with the code, I realized that placing parentheses around each of the not defined() calls leads to the desired result:

 if((not defined($k{"foo"})) && (not defined($k{"bar"}))){print "Not Defined"} 

I suppose this has something to do with operator precedence, but can anyone explain what exactly is going on?

+8
perl
source share
1 answer

Priority issue.

 not defined($k{"foo"}) && not defined($k{"bar"}) 

means

 not ( defined($k{"foo"}) && not defined($k{"bar"}) ) 

which is equivalent to

 !defined($k{"foo"}) || defined($k{"bar"}) 

when do you really 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 called "Perl", not "PERL".

+22
source share

All Articles