Comparing strings
Strings use word-like operators such as eq and lt instead of the math symbols.
In this page:
Comparing strings
The string comparison operators are eq, ne, lt, gt, le and ge, and cmp returns -1, 0 or 1. They compare character by character using the character codes, so uppercase letters sort before lowercase ones. Using the numeric operators like == on non-numeric strings produces warnings and compares their numeric values.
Note:
Compare case-insensitively by lowercasing both sides with lc.
Example: Comparing strings
use strict;
use warnings;
print "eq: ", ("perl" eq "perl" ? "same" : "different"), "\n";
print "ne: ", ("perl" ne "Perl" ? "different" : "same"), "\n";
print "lt: ", ("apple" lt "banana" ? "yes" : "no"), "\n";
print "Zebra lt apple: ", ("Zebra" lt "apple" ? "yes" : "no"), "\n";
print "cmp: ", join(",", "a" cmp "b", "b" cmp "b", "c" cmp "b"), "\n";
print "case-insensitive: ", (lc("PERL") eq lc("perl") ? "equal" : "not equal"), "\n";
print "sorted: ", join(" ", sort qw(banana Apple cherry apple)), "\n";
print "sorted ignoring case: ", join(" ", sort { lc($a) cmp lc($b) or $a cmp $b } qw(banana Apple cherry apple)), "\n";
# Output:
# eq: same
# ne: different
# lt: yes
# Zebra lt apple: yes
# cmp: -1,0,1
# case-insensitive: equal
# sorted: Apple apple banana cherry
# sorted ignoring case: Apple apple banana cherry
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using == to compare strings
- Forgetting that "Zebra" sorts before "apple"
- Comparing text with < instead of lt
Chapter Summary
- eq and ne test equality of strings
- lt gt le ge order strings
- cmp returns -1, 0 or 1
- Uppercase sorts before lowercase
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: