Open In App

Perl | cmp Operator

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report
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 Perl
#!/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 Perl
#!/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 Perl
#!/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

Explore