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

The following snippet is not working as expected:

if(not defined($k{"foo"}) && not defined($k{"bar"})){
    print "Not defined\n";
    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"})


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"})


  • !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".

Need Your Help

What does -1 mean in numpy reshape?

python numpy

A numpy matrix can be reshaped into a vector using reshape function with parameter -1. But I don't know what -1 means here.

String.strip() in Python

python string strip

While learning about python, I came upon this code, which takes a text file, splits each line into an array, and inserts it into a custom dictionary, where the array[0] is the key and array[1] is the