Chapter 6. Comparators, Sorting, and Hashes

Frossie Economou

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.

Table 6-1. Perl’s comparators

Number

String

Meaning

==

eq

Equal

!=

ne

Not equal

<

lt

Less than

>

gt

Greater than

<=

le

less or equal

>=

ge

Greater or equal

<=>

cmp

compare

You’ve probably seen them all before, with the possible exception of <=> and cmp.

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)

The expression $foo <=> $bar returns –1, 0, or 1 depending on whether $foo is smaller, equal to, or greater than $bar.

cmp behaves the same way as <=>, but it operates on strings instead of numbers.

Sorting

Comparators are often used to help sort a list of numbers or strings. Perl’s sort function expects ...

Get Computer Science & Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.