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

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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");

chevron_right


Output:

Comparison of $a and $b returns -1

Example 2: When String1 is equal to String2

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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");

chevron_right


Output:

Comparison of $a and $b returns 0

Example 3: When String1 is greater than String2

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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");

chevron_right


Output:

Comparison of $a and $b returns 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.