in reply to Why does this string comparison compares "numerically" and can I rely on this in general?

So, why does "eq" work like this

Because the internal representation of the two numbers is the same. Just because your code uses different formats to specify them does not affect how they are stored internally. Try this version of your code to see the values:

perl -we '$a = 1e-3; $b = 0.001; if ( $a eq $b ) { print "$a and $b ar +e equal.\n" }'

BTW, try to avoid $a and $b for arbitrary variables in real code because they have special meanings for sorting.

  • Comment on Re: Why does this string comparison compares "numerically" and can I rely on this in general?
  • Download Code

Replies are listed 'Best First'.
Re^2: Why does this string comparison compares "numerically" and can I rely on this in general?
by swl (Prior) on Apr 30, 2018 at 09:50 UTC

    The stringified form also depends if the values began as strings or numbers.

    $x = '1e-3'; $y = 0.001; if ( $x eq $y ) { print "$x and $y are equal.\n" } else { print "$x and $y are not equal" } print "\n"; $x = $x + 0; if ( $x eq $y ) { print "$x and $y are equal.\n" } else { print "$x and $y are not equal" }
    Result is:
    1e-3 and 0.001 are not equal 0.001 and 0.001 are equal.

    In the first comparison, $x is a string. In the second comparison, $x is numeric before it is stringified for comparison.

    The Scalar::Util documentation is useful here. https://perldoc.perl.org/Scalar/Util.html#isdual