Comparing scalars in Perl

In the previous part of the Perl tutorial
we introduced scalars and we saw how numbers
and strings are converted to each other on-the-fly. We even had
glimpse on a conditional if statement but we have not seen how
to compare two scalars. That's what this part is about.

Given two variables $x and $y how can we compare them?
Are 1, 1.0 and 1.00 equal? What about "1.00" ?
What is bigger "foo" or "bar"?

Two sets of comparison operators

Perl has two sets of comparison operators. As we saw with the
binary operators of addition (+), concatenation (.) and repetition (x),
here too, the operator is what defines how the operands behave and
how they are compared.

The two sets of operators are as follows:

Numeric String Meaning
== eq equal
!= ne not equal
< lt less than
> gt greater than
<= le less than or equal
>= ge greater than or equal

The operators on the left will compare the values as numbers while
the operators on the right (the middle column) will compare the
values based on the ASCII table or based on the current locale.

In this simple case Perl will print TRUE as the == operator compares the two
numbers and Perl does not care if the number is written as an integer or as a
floating point number.

A more interesting situation will be comparing

"12.0" == 12

which is also TRUE as the == operator of Perl converts the string to a number.

2 < 3 is TRUE because < compares the two numbers.
2 lt 3 is also TRUE as 2 is before 3 in the ASCII table
12 > 3 is TRUE obviously.
12 gt 3 will give you FALSE

This might be surprising for some people at first but if you think about it, the
way Perl compares the two strings is character by character. So it compares "1" to "3"
and as they are different and "1" is before "3" in the ASCII table Perl decides at
this point that 12 as a string is smaller than 3 as a string.

You have to make sure you compare things as you really want them!

"foo" == "bar" will be TRUE

It will also give you two warnings if(!) you enabled warnings by use warnings.
The reason for the warning is that you are using two strings as numbers in the numerical ==
comparison and that's what generates the warnings. As mentioned in the previous part
Perl will look at the left hand side of each string and convert them to the numbers it
sees there. As both strings start with a letter they will be both converted to 0.
0 == 0 so that's why we get true.

OTOH:

"foo" eq "bar" FALSE

So you have to make sure you compare values as you want them to be compared!