in reply to Re: How to determine a variable value is a number
in thread How to determine a variable value is a number

Interesting. Let me know if I've got this strait:
#!/usr/bin/perl -w use strict; sub i_am_a_number { shift; no warnings; # += 0 on a string sets off a warning # make sure that zero is counted as a number # ($_ += 0) alone fails on zero. if (/^\d+$/ || ($_ += 0)) { return 1; } return 0; } ############################################################# # take the sub on a test spin my @list = (035, 35, +19, 12, "045", -2, 5.5, 0, -34.530, "hi!"); for (@list) { if (i_am_a_number($_)) { print "$_ is a number!\n"; } }
Does this pass muster for zero, signed, and float type numbers?
()-()
 \"/
  `                                                     

Replies are listed 'Best First'.
Re3: How to determine a variable value is a number
by blakem (Monsignor) on Sep 19, 2002 at 11:07 UTC
    I don't think that passes muster.... Prove me wrong, but I believe that the expression
    i_am_a_number($_) || i_am_a_number($_)
    will always be true, no matter what value you choose. You might want to rethink what $_ += 0 does for non numbers, especially ones like "12isnotanumber".

    -Blake

      Absolutely right! Using $_ in the sub is bad and "15not" += 0; becomes 15. At the time I was just trying to understand the advice given in Far More Than Everything You've Ever Wanted to Know About... I must confess that I don't get it. Applying the advice given doesn't seem to work in all cases and so of not much use. Using Regex::Common is far and away the best solution that I have found.

      New version of the code that still doesn't work.

      #!/usr/bin/perl -w use strict; sub i_am_a_number { my $val = shift; no warnings; # += 0 on a string sets off a warning # make sure that zero is counted as a number # ($_ += 0) alone fails on zero. if ($val =~ /^\d+$/ || ($val += 0)) { return 1; } return 0; } ############################################################# # take the sub on a test spin my @list = ( # Zeros 0.00, .00, 0. , 0, -0, 00, # Integers 035, 35, +19, "045 ", " 045", -2, #Floats .15, 5.5, -34.530, # Not numbers " 0 1 ", " 0 0 ", " 24 0 ", " 15hi ", "2isnotanumber", "hi!" ); for (@list) { if (i_am_a_number($_) || i_am_a_number($_)) { print "$_ is a number!\n"; } else { print "$_ is not a number!\n"; } }
      ()-()
       \"/
        `