8

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?

Community
  • 1
  • 1
ealeon
  • 12,074
  • 24
  • 92
  • 173

2 Answers2

15

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.

jh314
  • 27,144
  • 16
  • 62
  • 82
4

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

Tom Williams
  • 378
  • 1
  • 5