Perl Tutorial Perl References

Perl - String comparison operators example



The example below illustrates the usage of Perl string comparison operators: eq, ne, gt, lt, ge, le, cmp.

$a = "abc";
$b = "xyz";

print("\$a == \$b: ".($a == $b ? true : false)."\n");
print("\$a != \$b: ".($a != $b ? true : false)."\n");
print("\$a < \$b: ".($a < $b ? true : false)."\n");
print("\$a > \$b: ".($a > $b ? true : false)."\n");
print("\$a <= \$b: ".($a <= $b ? true : false)."\n");
print("\$a >= \$b: ".($a >= $b ? true : false)."\n");

print("\nComparison Operator\n");
print("\$a cmp \$b: ".($a cmp $b)."\n");
print("\$a cmp \$a: ".($a cmp $a)."\n");
print("\$b cmp \$a: ".($b cmp $a)."\n");

The output of the above code will be:

$a == $b: true
$a != $b: false
$a < $b: false
$a > $b: false
$a <= $b: true
$a >= $b: true

Comparison Operator
$a cmp $b: -1
$a cmp $a: 0
$b cmp $a: 1

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

sub range_func {
  #passing argument
  $x = $_[0];

  #&& operator is used to combine conditions
  #returns true only when x ge "d" and $x le "p"
  if($x ge "d" && $x le "p") {
    print("$x belongs to range ['d', 'p'].\n"); 
  } else {
    print("$x do not belongs to range ['d', 'p'].\n");
  }
}

range_func("a");
range_func("g");
range_func("z");

The output of the above code will be:

a do not belongs to range ['d', 'p'].
g belongs to range ['d', 'p'].
z do not belongs to range ['d', 'p'].

❮ Perl - Operators