Open In App

Perl | cmp Operator

cmp operator in Perl is a string equality comparison operator used to compare if the two strings placed left and right to this operator are equal or less than the other.

Syntax: string1 cmp string2



Returns: -1 if string1 is less, 0 if equal and 1 if greater than string2.

Example 1: When String1 is less than String2




#!/usr/local/bin/perl
  
# Initializing strings
$a = "Geeks";
$b = "Welcome";
  
# Comparing strings
$c = $a cmp $b;
  
# Printing the comparison result
print("Comparison of \$a and \$b returns $c");

Output:

Comparison of $a and $b returns -1

Example 2: When String1 is equal to String2




#!/usr/local/bin/perl
  
# Initializing strings
$a = "Welcome";
$b = "Welcome";
  
# Comparing strings
$c = $a cmp $b;
  
# Printing the comparison result
print("Comparison of \$a and \$b returns $c");

Output:
Comparison of $a and $b returns 0

Example 3: When String1 is greater than String2




#!/usr/local/bin/perl
  
# Initializing strings
$a = "Welcome";
$b = "Geeks";
  
# Comparing strings
$c = $a cmp $b;
  
# Printing the comparison result
print("Comparison of \$a and \$b returns $c");

Output:
Comparison of $a and $b returns 1

Article Tags :