Perl String Equality Operators Example



Below is a list of equity operators. Assume variable $a holds "abc" and variable $b holds "xyz" then, lets check the following string equality operators −

Sr.No. Operator & Description
1

lt

Returns true if the left argument is stringwise less than the right argument.

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

2

gt

Returns true if the left argument is stringwise greater than the right argument.

Example − ($a gt $b) is false.

3

le

Returns true if the left argument is stringwise less than or equal to the right argument.

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

4

ge

Returns true if the left argument is stringwise greater than or equal to the right argument.

Example − ($a ge $b) is false.

5

eq

Returns true if the left argument is stringwise equal to the right argument.

Example − ($a eq $b) is false.

6

ne

Returns true if the left argument is stringwise not equal to the right argument.

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

7

cmp

Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.

Example − ($a cmp $b) is -1.

Example

Try the following example to understand all the string 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 = "abc";
$b = "xyz";

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

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

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

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

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

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

$c = $a cmp $b;
print "\$a cmp \$b returns $c\n";

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

Value of $a = abc and value of $b = xyz
abc lt $b is true
$a gt $b is not true
$a le $b is true
$a ge $b is not true
$a ne $b is true
$a cmp $b returns -1
perl_operators.htm
Advertisements