Some Numeric and String Comparison Operators
Comparison, or relational, operators tell us how two scalar values (numbers or strings) relate to
each other. There are two sets of operators: one does numeric comparison
and the other does string comparison. (In either case, the arguments
will be “coerced” to have the appropriate type first.) Assuming left and
right arguments of $a and $b, Table 1-5 shows
us what we have.
Table 1-5. Comparison operators
| Comparison | Numeric | String | Return Value |
|---|---|---|---|
| Equal | == | eq | True if $a is equal to $b |
| Not equal | != | ne | True if $a is not equal to $b |
| Less than | < | lt | True if $a is less than $b |
| Greater than | > | gt | True if $a is greater than $b |
| Less than or equal | <= | le | True if $a not greater than $b |
| Greater than or equal | >= | ge | True if $a not less than $b |
| Comparison | <=> | cmp | 0 if equal, 1 if $a
greater, −1 if $b
greater |
The last pair of operators (<=> and cmp) are entirely redundant with the earlier
operators. However, they’re incredibly useful in sort subroutines (see Chapter 27).[27]
[27] Some folks feel that such redundancy is evil because it keeps a language from being minimalistic, or orthogonal. But Perl isn’t an orthogonal language; it’s a diagonal language. By this we mean that Perl doesn’t force you to always go at right angles. Sometimes you just want to follow the hypotenuse of the triangle to get where you’re going. TMTOWTDI is about shortcuts. Shortcuts are about programmer efficiency.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access