Perl Numeric Equality Operators Example

Advertisements


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

OperatorDescriptionExample
== Checks if the value of two operands are equal or not, if yes then condition becomes true.($a == $b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.($a != $b) is true.
<=> 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.($a <=> $b) returns -1.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.($a > $b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.($a < $b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.($a >= $b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.($a <= $b) is true.

Example

Try following example to understand all the numeric equality operators available in Perl. Copy and paste 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 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


Advertisements
Advertisements