Perl’s language has a comparison operator to test variables for equal or not.

Comparison operators are binary operators that apply to two operands and return a boolean value in Perl.

It contains two types of the comparison operator.

  • Equality operator: Used to Check whether two operands are equal or not.
  • Relation Operator: used for checking one operand is compared with other

These operators apply to numbers and strings.

What are the Comparison operators in Perl?

Comparison operators apply to two operands and return a boolean value always. It always returns boolean values and is used in conditional if statements.


operand1 comparison-operator operand2

Perl String and Numerical Comparison Operators

|Parameter | Number Symbol |String Symbol |Description |:——–| ————— | |Equal | == |eq|Both operands are equal or not, return boolean value | |Not Equal | != |ne|Both operands are equal or not,return boolean value | |Comparison | <=> |cmp|Used in Sorting for comparison of one value to another| |Less Than | < |lt|Used in One value is less than other Comparison| |Greater Than | > |gt|Used in One value is greater than other Comparison| |Less Than Equal| <= |le|Used in One value is less than or equal to other comparisons | |Greater Than or Equal | >= |ge|Used in One value is greater than or equal other comparisons |

Perl Comparison Operators Examples

This is an example of the logical operator with code In Perl, Boolean values are not true and false. It returns 1 for true, empty, or zero for false.

my $opearnd1 = 10;
my  $operand2 = 20;
# Comparision Operators example
$operand1 > $operand2;  ## 1
$operand1 < $operand2;  ## empty
$operand1 >= $operand2;  ## 1
$operand1 <= $operand2;  ## empty
$operand1 == $operand2;  ## empty
$operand1 != $operand2;  ## 1
$operand1 <=> $operand2;  ## -1
$operand1 < $operand2;  ## empty

Spaceship operator in Perl

The operator is <=>, also called the comparison operator


operand1 `<=>` operand2

If Operand1 is bigger than operand2, It returns 1 if Operand2 is greater than Operand1, Returns -1 Returns 0 if both are equal.

Here is an example

$v1 = "a";
$v2 = "b";
$v3  = "z";

print($v1 cmp $v2, "\n"); # -1
print($v2 cmp $v2, "\n"); # 0
print($v3 cmp $v1, "\n");# 1

Perl Comparison Operators Precedence

Precedence applied to a group of conditional operators.

During execution, One of them takes first for execution than others.

It always executes from left to right when there are multiple conditions.

my $opearnd1 = 2;
my  $operand2 = 2;
my  $operand3 = 13;

print  ($opearnd1 == $opearnd2) == $opearnd3

In the above,$opearnd1 && $opearnd2 evaluated and result is applied with or operator of $operand3, return boolean values