On the accepted answer for String compare in Perl with "eq" vs "=="
it says that First, eq is for comparing strings; == is for comparing numbers.
"== does a numeric comparison: it converts both arguments to a number and then compares them."
"eq does a string comparison: the two arguments must match lexically (case-sensitive)"
You can ONLY use eq for comparing strings but
both eq AND == works for comparing numbers
numbers are subset of strings so i just dont understand why you would ever use ==
Is there a reason why you would want to use == for comparing numeric values over just using eq for all?
Here is an example of why you might want ==
:
$a = "3.0";
print "eq" if $a eq "3"; # this will not print
print "==" if $a == 3; # this will print
3.0 is numerically equal to 3, so if you want them to be equal, use ==
. If you want to do string comparisons, then "3.0"
is not equal to "3", so in this case you would use eq
. Finally, ==
is a cheaper operation than eq
.
String comparisons are just plain different, especially with numbers.
@s_num=sort {$a <=> $b} (20,100,3); # uses explicit numeric comparison
print "@s_num\n"; # prints 3 20 100, like we expect
@s_char=sort (20,100,3); # uses implicit string comparison
print "@s_char\n"; # prints 100 20 3, not so good.
-Tom Williams
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With