Item 4: String and numeric comparisons are different.

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:

 'a' lt 'b'  'a' eq 'A'  "joseph" eq "joseph "  "H" cmp "He" 



FALSEspaces count.

-1 cmp operator.

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:

 0 < 5  10 == 10.0  10 <=> 9.5 



1 "spaceship" operator.

The spaceship operator <=> [1] is like cmp , except that it compares its arguments numerically .

[1] Is it Darth Vader's fighter? Or a starbase from the old character-based Star Trek games ? You decide.

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:

 '10' gt '2'  "10.0" eq "10"  'abc' == 'def' 

FALSE '1' sorts before '2' .

FALSEdifferent strings.

TRUEboth look like to == .

The kind of mistake this leads to is:

Don't compare strings with numeric operators, or vice versa.

 $hacker = 'joebloe';  if ($user == $hacker) {    deny_access();  } 

WRONG == used on strings.

Oopsmost strings look like to == , so nobody gets on.

Perl's sort operator uses string comparisons by default. Don't use string comparisons to sort numbers! See Item 14 for more about sorting.

Effective Perl Programming. Writing Better Programs with Perl
Effective Perl Programming: Writing Better Programs with Perl
ISBN: 0201419750
EAN: 2147483647
Year: 1996
Pages: 116

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: