In Perl, why are there separate operators for string comparison (eq
, ne
) vs. numeric comparison (==
, !=
)? Why use two separate sets of operators instead of using a single operator for both string and numeric comparisons?
Asked
Active
Viewed 243 times
1

ThisSuitIsBlackNot
- 23,492
- 9
- 63
- 110

Cisum Inas
- 11,552
- 11
- 40
- 55
-
1It has these operators so it doesn't have to reinvent the wheel with `===` and `!==` operators, which btw doesn't quite solve the comparison problem. – mpapec Oct 06 '14 at 15:12
-
4Perl has different operators for numeric and string comparison because numeric and string comparison are different operations. Better to ask, why do so many other languages use one operator for dissimilar things, even the ones without a type system that would make it unambiguous? – hobbs Oct 06 '14 at 15:12
-
7Short answer: **Because Perl doesn't know if a value is a number or not.** To Perl, the numeric value `2` can be just as easily be stored as a string as it be stored as a signed int. – ikegami Oct 06 '14 at 15:22
-
3Compare this to Javascript where, say, the `+` operator is defined to do different things on strings and numbers, and the annoyance and confusion that causes. – tobyink Oct 06 '14 at 15:40
1 Answers
3
Perl does automatic type conversion whenever it feels like it to evaluate an expression. This requires two operators so the programmer can distinguish between string and numeric comparisons:
print "eq" if "02" eq "2"; # string comparison -- no output
print "==" if "02" == "2"; # numeric comparison -- will print "=="
The above was taken from this thread on PerlMonks. Here's some other info from that thread:
- One reason to use
==
rather thaneq
is so that you can get warnings if something non-numerical is used where you expect a number. - One reason to use
eq
rather than==
is that string conversions lose a few decimal places, so you put off hitting spurious inequalities due to floating-point rounding errors. - Consider writing
2 == $val
rather than$val == 2
. It looks odd, but that way the common typo of=
rather than==
will give you an immediate compilation error rather than a nasty bug.

Ted Hopp
- 232,168
- 48
- 399
- 521
-
string conversions do not lose a few decimal places, they lose a partial decimal place. – ysth Oct 06 '14 at 16:20
-
(e.g. a 64-bit floating point number with a 53-bit significand can store numbers with a precision of 15.9 decimal digits but we stringify it to 15 decimal digits) – ysth Oct 06 '14 at 16:25
-
[Warnings will catch that last case before it becomes a nasty bug](https://eval.in/202162), but that is a clever way of transforming a runtime warning to a compiletime error (at the cost of a slightly less explanatory error message, which [omits the most salient part of the error](https://eval.in/202163) (the `2 = `). – Slade Oct 06 '14 at 17:15
-