Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl's "not" operator not working as expected with the defined() function

Tags:

perl

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?

like image 844
terdon Avatar asked Oct 18 '12 15:10

terdon


1 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".

like image 94
ikegami Avatar answered Oct 04 '22 12:10

ikegami