Perl Tutorial Perl References

Perl - Numeric comparison operators example



The example below illustrates the usage of Perl numeric comparison operators: ==, !=, >, <, >=, <=, <=>.

print("10 == 10: ".(10 == 10 ? true : false)."\n");
print("10 != 10: ".(10 != 10 ? true : false)."\n");
print("10 < 20: ".(10 < 20 ? true : false)."\n");
print("10 > 20: ".(10 > 20 ? true : false)."\n");
print("10 <= 20: ".(10 <= 20 ? true : false)."\n");
print("10 >= 20: ".(10 >= 20 ? true : false)."\n");

print("\nComparison Operator\n");
print("10 <=> 20: ".(10 <=> 20)."\n");
print("20 <=> 20: ".(20 <=> 20)."\n");
print("30 <=> 20: ".(30 <=> 20)."\n");

The output of the above code will be:

10 == 10: true
10 != 10: false
10 < 20: true
10 > 20: false
10 <= 20: true
10 >= 20: false

Comparison Operator
10 <=> 20: -1
20 <=> 20: 0
30 <=> 20: 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 >= 10 and x <= 25
  if($x >= 10 && $x <= 25) {
    print("$x belongs to range [10, 25].\n"); 
  } else {
    print("$x do not belongs to range [10, 25].\n");
  }
}

range_func(15);
range_func(25);
range_func(50);

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ Perl - Operators