$a = 1e-3; $b = 0.001; if ( $a eq $b ) { ...
Note that this doesn't really have anything to do with eq or ==, but with how Perl handles numeric literals in its source code - they are converted to Perl's internal representation first.
# force numbers to strings before printing: $ perl -wMstrict -le 'print "".1e-3; print "".0.001; print "".0.0_0_1; print "".0x1.0624dd2f1a9fcp-10' 0.001 0.001 0.001 0.001 # edited for brevity: $ perl -wMstrict -MDevel::Peek -le 'Dump( 1e-3 )' NV = 0.001 $ perl -wMstrict -MDevel::Peek -le 'Dump( 0.001 )' NV = 0.001 $ perl -wMstrict -MDevel::Peek -le 'Dump( 0.0_0_1 )' NV = 0.001 $ perl -wMstrict -MDevel::Peek -le 'Dump( 0x1.0624dd2f1a9fcp-10 )' NV = 0.001
would two numbers always numerically oompared by "eq"
If I take the question to mean "does eq do numeric comparisons automatically when presented with numbers", the answer is no, it always converts its operands to strings first (I'm ignoring overloading here).
can I rely on this in general
But my question would be: Why would you want to rely on this? If you want to do a numeric comparison, you should use the numeric == (always keeping in mind the limitations of floating-point numbers!*), and if you want to know if two values converted to strings are equal, use eq - and looking at the above, eq's behavior makes sense here.
At the moment, I can't think of a case where one would want to do such an "automatic numeric comparison". Could this be an XY problem - are you perhaps trying to do something with user input? (Update: If you want a number to retain its formatting, you need to store it as a string instead of a number.)
* Update: And if you want to know whether two numbers are approximately equal:
$ perl -wMstrict -le ' if ( sprintf("%.3f",0.001) eq sprintf("%.3f",0.001001) ) { print "yes" } else { print "no" }' yes
In reply to Re: Why does this string comparison compares "numerically" and can I rely on this in general?
by haukex
in thread Why does this string comparison compares "numerically" and can I rely on this in general?
by Bloehdian
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |