Perl has two completely different sets of comparison operators, one for comparing strings and one for comparing numbers . It's worthwhile to know the difference and to keep them straight, because using the wrong comparison operator can be the source of hard-to-find bugs . The operators used to compare strings are made up of letters and look like words, or like FORTRAN. Strings are compared "ASCIIbetically"that is, by comparing the ASCII values of the characters in the strings, including case, spaces, and the like:
The cmp operator does a string comparison and returns -1 , , or 1 , depending on whether its left argument is less than, equal to, or greater than its right argument, respectively. It is particularly useful for sorting (see Item 14). Numeric comparison operators are made up of punctuation and look like algebra, or like C:
The spaceship operator <=> [1] is like cmp , except that it compares its arguments numerically .
String comparison operators should not be used for comparing numbers, because they don't compare numbers properly. (Unless your definition of "properly" puts "10" before "2" .) The same applies for numeric operators used to compare strings:
The kind of mistake this leads to is: Don't compare strings with numeric operators, or vice versa.
Perl's sort operator uses string comparisons by default. Don't use string comparisons to sort numbers! See Item 14 for more about sorting. |