packetie packetie - 15 days ago 10
Perl Question

perl compare strings with "=="

In perl, one should compare two strings with "eq" or "ne" etc.

I am a little surprised the following code snippet will print "yes".

$str = "aJohn";
$x = substr($str, 1);
if ($x == "John") {
print "yes\n";
}


My perl has version v5.18.4 on Ubuntu.

Is there a case where the "==" on two strings produce a different result from "eq"?
Thanks.

Answer

"foo" == "bar" is true. "foo" eq "bar" is false.

The reason for this: == is numeric comparison. "foo" and "bar" are both numerically evaluate to 0 (like "17foo" evaluates numerically to 17); since 0 == 0, "foo" == "bar". This is not normally the operation you are looking for.