Logical Operators

Let's discuss logical operators and how we can use them to evaluate our conditions in Perl.

What are logical operators?

Logical operators are used for combining conditional statements. This means that the program can take a decision based on multiple conditions. We will learn more about conditional statements later. But for now, suffice it to say that conditional statements are those that can either be “true” or “false”.

Types of logical operators

There are three logical operators:

  • && or and
  • || or or
  • ! or not

The and operator

The and or && operator returns true if all the statements are true. It returns false if one or more statements are false. Let’s say that we have two statements a and b. The following table illustrates this behavior:

a b a && b or a and b
true true true
true false false
false true false
false false false

Run the code below to see how this works:

Press + to interact
$x=7;
$y=6;
$z=2;
if($x > $y && $x > $z) {
print "You're in IF statement";
}
else {
print "You're in ELSE statement";
}

The or operator

The or or || operator returns true if one or more of the conditional statements are true. It returns false if all the conditions are false. The following table illustrates this behavior.

a b a || b or a or b
true true true
true false true
false true true
false false false

Run the code below to see how this works:

Press + to interact
$x = 7;
$y = 10;
$z = 2;
if($x > $y || $x > $z){
print "Successful!";
}
else {
print "Failed!";
}

The not operator

The not or ! operator returns true if the input statement is false and vice versa. The following table illustrates this behavior.

a !a
true false
false true

Run the code below to see how this works:

Press + to interact
$x = 7;
$y = 10;
if(!($x > $y)){
print "Passed!";
}
else {
print "Failed!";
}

In Perl, the && , ||, and ! operators have higher precedence than and, or, and not respectively, as evident from the table below:

Evaluation Result Evaluated as
$e = true && false False $e = (true && false)
$e = true and false True ($e = true) && false

Because of this, it’s safer to use &&, ||, and ! instead of and, or, and not respectively.