in reply to problem with variables

Wouldn't
if ($a == $b) { ... }

Be correctly written as:
if ($a eq $b) { ... }

?

Replies are listed 'Best First'.
Re^2: problem with variables
by muntfish (Chaplain) on Oct 19, 2005 at 11:22 UTC

    No, eq is for string comparison, which definitely wouldn't work here. In Perl == does numeric comparison.

    See perlop.

    You may be thinking of (korn) shell where it's the other way round.


    s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&
      Works fine for me:
      #!/usr/bin/perl use strict; use warnings; my $num1 = 1234.56789; my $num2 = 1234.56789111; if ( $num1 == $num2 ) { print "equal.\n"; } else { print "Please don't try to check for equality of floats that way.\ +n"; } if ( sprintf( "%.3f", $num1 ) == sprintf( "%.3f", $num2 ) ) { print "Yup, they show up as equal.\n"; } if ( sprintf( "%.3f", $num1 ) eq sprintf( "%.3f", $num2 ) ) { print "Yup. This works too.\n"; }
      output:
      Please don't try to check for equality of floats that way. Yup, they show up as equal. Yup. This works too.
        Actually, now that brain is in gear, I think you *always* want to use eq rather than == for comparing floats. If you use
        sprintf( "%.3f", $num1 ) == sprintf( "%.3f", $num2 )
        that just puts you right back to where you started: comparing floats with ==.