← Back to Perl Course | Chapter 3: Strings | Lesson 3 of 7

Comparing strings

Strings use word-like operators such as eq and lt instead of the math symbols.

In this page:

  1. Comparing strings

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

perl
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
Common Mistakes
  1. Using == to compare strings
  2. Forgetting that "Zebra" sorts before "apple"
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.