Relational Operators
Learn all about relational operators in this lesson, especially the spaceship relational operator.
We'll cover the following
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:
$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:
$a = 6;$b = 8;if($b > $a){ # greater thanprint ("Yes -- $b is greater than $a\n");}else{print ("No -- $b is not greater than $a\n");}if($a < $b){ # Less thanprint ("Yes -- $a less than $b\n");}else{print ("No -- $a is not less than $b\n");}if($a <= $b){ # Less than or equal toprint ("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 toprint ("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:
# Integersprint ((1 <=> 1).","); #prints 0print ((1 <=> 2).","); #prints -1print ((2 <=> 1)); #prints 1print "\n"; #skips to next line# Floatsprint ((1.5 <=> 1.5).","); #prints 0print ((1.5 <=> 2.5).","); #prints -1print (2.5 <=> 1.5); #prints 1print "\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:
# Stringsprint (("a" cmp "a").","); #prints 0print (("a" cmp "b").","); #prints -1print ("b" cmp "a"); #prints 1