Relational Operators

Learn all about relational operators in this lesson, especially the spaceship relational operator.

Basic operators

Comparison operators allow you to compare two values. The following table illustrates the different comparison operators in Perl:

Operator Name Example
== Equal a==b
!= Not Equal a!=b
< Less than a<b
> Greater than a>b
>= Greater than or equal to a>=b
<= Less than or equal to a<=b

Example

Run the code snippet below to see how == and != work:

Press + to interact
$a = 4;
$b = 4;
if ($a != $b) {
print 'a and b are not equal'; # this will not be printed
}
if ($a == $b) {
print 'a and b are equal';
}

In the above code snippet, the == operator returns “true” because 4 and 5 are not equal. The if statement checks the relational expression and takes the decision based on the truthfulness of the expression. If the expression is true, then the following statement is executed and the else part is skipped (even if it exists). If the expression is false, then the following statement is skipped and the else part is executed (if it exists). We’ll cover the if statement in detail in the next chapter.

Let us now examine the remaining relational operators:

Press + to interact
$a = 6;
$b = 8;
if($b > $a){ # greater than
print ("Yes -- $b is greater than $a\n");
}
else{
print ("No -- $b is not greater than $a\n");
}
if($a < $b){ # Less than
print ("Yes -- $a less than $b\n");
}
else{
print ("No -- $a is not less than $b\n");
}
if($a <= $b){ # Less than or equal to
print ("Yes -- $a is less than or equal to $b\n");
}
else{
print ("No -- $a is not less than or equal to $b\n");
}
if($b >= $a){ # Greater than or equal to
print ("Yes -- $b is greater than or equal to $a\n");
}
else{
print ("No -- $b is not greater than or equal to $a\n");
}

Spaceship operator

The spaceship operator (<=>) is a number comparison operator. It

  • returns 1 if the first expression is greater than the second expression.
  • returns -1 if the first expression is lesser than the second expression.
  • returns 0 if the first expression is equal to the second expression.

Run the code snippet below to see how it works:

Press + to interact
# Integers
print ((1 <=> 1).","); #prints 0
print ((1 <=> 2).","); #prints -1
print ((2 <=> 1)); #prints 1
print "\n"; #skips to next line
# Floats
print ((1.5 <=> 1.5).","); #prints 0
print ((1.5 <=> 2.5).","); #prints -1
print (2.5 <=> 1.5); #prints 1
print "\n"; #skips to next line

cmp operator

The cmp operator is just like the <=> operator, except that it is constructed to work with the string operands.

Run the example below to get a clear picture:

Press + to interact
# Strings
print (("a" cmp "a").","); #prints 0
print (("a" cmp "b").","); #prints -1
print ("b" cmp "a"); #prints 1