Perl Numeric Equality Operators Example



These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators −

Sr.No. Operator & Description
1

== (equal to)

Checks if the value of two operands are equal or not, if yes then condition becomes true.

Example − ($a == $b) is not true.

2

!= (not equal to)

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

Example − ($a != $b) is true.

3

<=>

Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument.

Example − ($a <=> $b) returns -1.

4

> (greater than)

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

Example − ($a > $b) is not true.

5

< (less than)

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

Example − ($a < $b) is true.

6

>= (greater than or equal to)

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

Example − ($a >= $b) is not true.

7

<= (less than or equal to)

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

Example − ($a <= $b) is true.

Example

Try the following example to understand all the numeric equality operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program.

#!/usr/local/bin/perl
 
$a = 21;
$b = 10;

print "Value of \$a = $a and value of \$b = $b\n";

if( $a == $b ) {
   print "$a == \$b is true\n";
} else {
   print "\$a == \$b is not true\n";
}

if( $a != $b ) {
   print "\$a != \$b is true\n";
} else {
   print "\$a != \$b is not true\n";
}

$c = $a <=> $b;
print "\$a <=> \$b returns $c\n";

if( $a > $b ) {
   print "\$a > \$b is true\n";
} else {
   print "\$a > \$b is not true\n";
}

if( $a >= $b ) {
   print "\$a >= \$b is true\n";
} else {
   print "\$a >= \$b is not true\n";
}

if( $a < $b ) {
   print "\$a < \$b is true\n";
} else {
   print "\$a < \$b is not true\n";
}

if( $a <= $b ) {
   print "\$a <= \$b is true\n";
} else {
   print "\$a <= \$b is not true\n";
}

When the above code is executed, it produces the following result −

Value of $a = 21 and value of $b = 10
$a == $b is not true
$a != $b is true
$a <=> $b returns 1
$a > $b is true
$a >= $b is true
$a < $b is not true
$a <= $b is not true
perl_operators.htm
Advertisements