O'Reilly logo

Computer Science & Perl Programming by Jon Orwant

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required