in reply to Testing For Numberness Vs Stringness

What you are seeing is the fact that Perl will happily use a stringified number as a numerified string if it makes sense to do so. That is, to Perl, '3.0' (the string) is the same numerically as 3.0 (the number). It is also true that Perl will happily stringify a number where it makes sense to do so. Where this begins to break down is when you compare the number 3.0 with the string '3.0' using a string comparison. This fails because 3.0 (the number) is actually just 3 (the number). Stringified, that is '3' (the string). When you compare '3' eq '3.0', you are going to get inequality, since as strings go, they're not the same.


Dave

Replies are listed 'Best First'.
Re^2: Testing For Numberness Vs Stringness
by BrooklineTom (Novice) on Nov 27, 2004 at 17:35 UTC
    Hi Dave, thanks for your reply.

    I understand that this is what perl does. I fear this is very broken. I'm writing a test harness that needs to validate results of other routines. Since numbers and strings respond differently when compared by == and eq, the harness needs to be able to distinguish numbers from strings.

      Have sepperate functions for numeric vs stringy tests, then. The answer to "is 03 the same as 3" depends on intentions, and not any occult flags of the 3.0 and the 3 that your program could concivably read.

        When a test routine is recursing its way, scalar by scalar, through a possibly unknown data structure -- such as during a deep compare -- it can't decide whether to use a numeric vs stringy test. There are no "intentions" to know, and no metastructure (occult or not) to consult. Fortunately, as bgreenlea showed in his or her reply, no "occult flags" are needed -- the bit-by-bit comparison does the trick.