Chapter 6. Comparators, Sorting, and Hashes
Shall I compare thee to a summer’s day? Thou art more lovely and more temperate…
—William Shakespeare, Sonnet XVIII
“I’d like to know if I could compare you to a summer’s day. Because well, June 12th was quite nice, and…”
—Terry Pratchett, Wyrd Sisters
Perl has two types of comparators, so called because they compare something to something else. Half of them compare one number to another, and the other half compare strings. Don’t mix them! The comparators are shown in Table 6-1.
less or equal
Greater or equal
You’ve probably seen them all before, with the possible exception of <=> and
To see where these comparators come in handy, consider a series of questions posed to a politician:
Q. Will you raise taxes? ($newtax > $oldtax) A. No. Q. So you will lower taxes? ($newtax < $oldtax) A. No. Q. Ah, you'll keep them the same? ($newtax == $oldtax)
You could have combined all three questions into one, presuming your politician understands the <=> comparator:
Q. Will you raise/lower/maintain taxes? ($newtax <=> $oldtax)
$foo <=> $bar returns –1, 0, or 1 depending on whether
$foo is smaller, equal to, or greater than
cmp behaves the same way as <=>, but it operates on strings instead of numbers.
Comparators are often used to help sort a list of numbers or strings. Perl’s
sort function expects ...