Testing for equality in perl

Perl has two similar-sounding types of operators for testing whether two values are the same. This note describes the differences between them. Click here for the official documentation for these (and related) operators.

The "==" operator

The "==" operator tests to see whether the two values have the same numeric values. So, all the following return true:

1 == 1
2 == 02
3 == "3"
4 == "  04"
8 == 010   (but note: 8 == "010" does NOT return true)
"10" == "010"
17 == 0x11  (but: 17 == "0x11" does NOT return true)
0 == "0x11"
"hello" == 0
"hello" == "goodbye"
"12 days" == 12
1.5 == 1.5000
1.6 == "  01.60"

Using "==" when both values are numeric anyway has obvious results. But you should note from the above that even strings are compared numerically. Perl converts the string value into it's numeric value. However: note there are some limits to this, specifically in the area of interpreting octal and hex values contained within strings.

The "!=" operator

The "!=" operator is the opposite of "==" and returns false wherever "==" would return true (and visa-versa).

The "eq" operator

The "eq" operator tests for string equality. The following return true:

"hello" eq "hello"
0x11 eq 17

The following return false, even though the "==" equivalents returned true

4 eq " 04"
1.6 eq " 01.60"
"10" eq "010"
"hello" eq "goodbye"

Using "eq" when both values are strings has obvious results, but when one or both are numbers then some thought needs to be put into understanding what the results will be.

The "ne" operator

The "ne" operator is the opposite of "eq".

 

Scroll to Top