Perl String Equality Operators Example

Advertisements


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

OperatorDescriptionExample
lt Returns true if the left argument is stringwise less than the right argument. ($a lt $b) is true.
gtReturns true if the left argument is stringwise greater than the right argument. ($a gt $b) is false.
leReturns true if the left argument is stringwise less than or equal to the right argument. ($a le $b) is true.
geReturns true if the left argument is stringwise greater than or equal to the right argument. ($a ge $b) is false.
eqReturns true if the left argument is stringwise equal to the right argument. ($a eq $b) is false.
neReturns true if the left argument is stringwise not equal to the right argument. ($a ne $b) is true.
cmpReturns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. ($a cmp $b) is -1.

Example

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


Advertisements
Advertisements