Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl simple comparison == vs eq

Tags:

perl

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?

like image 674
ealeon Avatar asked Aug 07 '13 02:08

ealeon


2 Answers

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.

like image 95
jh314 Avatar answered Sep 22 '22 17:09

jh314


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

like image 45
Tom Williams Avatar answered Sep 21 '22 17:09

Tom Williams