in reply to Testing For Numberness Vs Stringness

Under which scenarios does the is_numeric subroutine above not work? I ran a little test and it seems to work fine:
foreach (3,'3',3.0,'3.0',3.1,'3.1') { print "$_ is ", is_numeric($_) ? '':'not ', "numeric\n"; } sub is_numeric { ($_[0] & ~ $_[0]) eq "0"; } $ ./is_numeric.pl 3 is numeric 3 is not numeric 3 is numeric 3.0 is not numeric 3.1 is numeric 3.1 is not numeric

-b

Replies are listed 'Best First'.
Re^2: Testing For Numberness Vs Stringness
by BrooklineTom (Novice) on Nov 27, 2004 at 17:41 UTC
    AHA! bgreenlee, you have helped me resolve my mystery. Here's what happened. I originally tested the results like this:
    my $a = 3.0; my $b = '3.0'; my $stringCompareResult = $a eq $b?'true':'false'; my $numberCompareResult = $a == $b?'true':'false'; sub is_numeric { ($_[0] & ~ $_[0]) eq "0"; } print ("\$stringCompareResult: $stringCompareResult\n"); print ("\$numberCompareResult: $numberCompareResult\n"); my $isNumericResultA = is_numeric($a)?'true':'false'; my $isNumericResultB = is_numeric($b)?'true':'false'; print ("\$isNumericResultA: $isNumericResultA\n"); print ("\$isNumericResultB: $isNumericResultB\n");
    When I ran this code, I got the following output:
    $stringCompareResult: false $numberCompareResult: true $isNumericResultA: true $isNumericResultB: true
    I see, now, thanks to your reply, that when I used $a and $b in the earlier comparison, the interpreter CHANGED their "type". I had forgetting that Perl does this.

    When I comment out the comparisons, and run just is_numeric, I get the same results as you. Thanks, bgreenlee!