next up previous contents
Next: Arrays and Lists Up: Scalar Data Previous: Operators for Numeric Scalar   Contents


Comparison Operators

Table 3.2 shows the comparison operators available in perl. Note that separate operators are provided for string and numeric comparisons; it is your responsibility to make sure that you use the appropriate one. (The -w flag (Section 1.5.1) can be very helpful in pointing out potential errors.) The reason that perl can't do its usual trick of figuring out how to convert between strings and numbers in this case is that there is no way to do so unambiguously. For example, consider the two strings "100" and "2". As strings, the first string is less than the second string, since the first string begins with a "1" and the second begins with a "2", and "1" comes before "2" when sorting things alphabetically. When the two values are compared as numbers, however, it is clear that 2 is less than 100. Thus, you'll have to be aware of what your goals are whenever you compare two values, whether they are strings or numeric.


Table 3.2: Comparison Operators
Function Numerical Character
Equality == eq
Non-equality != ne
Less than < lt
Greater than > gt
Less than or equal <= le
Greater than or equal >= ge
Comparison <=> cmp


Note that you need to be careful about your choice of operator, even when you are testing for equality. Consider the two values "20" and "20.0". As strings, these two values are different, while as numbers, they are the same.


next up previous contents
Next: Arrays and Lists Up: Scalar Data Previous: Operators for Numeric Scalar   Contents
Phil Spector 2002-10-18