mw55309 has asked for the wisdom of the Perl Monks concerning the following question:

Hi I need to know how to check if the value a variable holds CAN BE INTERPRETED AS A NUMBER. My vble can have values such as:

"NA"
2.34
0.234+E06

(note the last two ARE VALID numbers, the first is not)

How can I check to see if my vble holds a number or not?

Thanks

Replies are listed 'Best First'.
Re: Is a vble a number?
by Limbic~Region (Chancellor) on Oct 23, 2003 at 12:31 UTC
    mw55309,
    Scalar::Util has looks_like_a_number. Here is the source:
    sub looks_like_number { local $_ = shift; # checks from perlfaq4 return 1 unless defined; return 1 if (/^[+-]?\d+$/); # is a +/- integer return 1 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/); # +a C float return 1 if ($] >= 5.008 and /^(Inf(inity)?|NaN)$/i) or ($] >= 5.006 +001 and /^Inf$/i); 0; }
    As you can see, it handles the regex from the FAQ plus a few additional things.

    Cheers - L~R

Re: Is a vble a number?
by broquaint (Abbot) on Oct 23, 2003 at 11:09 UTC
    To be sure, you could always ask perl. Otherwise you could look into using the various number regexes found in the always useful Regexp::Common.
    HTH

    _________
    broquaint

Re: Is a vble a number?
by Abigail-II (Bishop) on Oct 23, 2003 at 11:06 UTC
Re: Is a vble a number?
by RMGir (Prior) on Oct 23, 2003 at 11:53 UTC
    Looking at the title, I couldn't figure out what mw55309 was asking.

    All I could think of was "vbles vobble but they don't fall down" :)

    By the way, "0.234+E06" isn't a valid number, or at least, it isn't 234000.

    perl won't complain, but it evaluates to 0.234. You probably meant "0.234E+06".

    Abigail-II is right, as usual; the regexen in the FAQ answer would catch that error.


    Mike
Re: Is a vble a number?
by zentara (Cardinal) on Oct 23, 2003 at 16:15 UTC
    #!/usr/bin/perl #gives correct output for your examples print is_numeric(10),"\n"; print is_numeric('3rd'),"\n"; print is_numeric("NA"),"\n"; print is_numeric(2.34),"\n"; print is_numeric(0.234+E06),"\n"; sub is_numeric { no warnings; use warnings FATAL => 'numeric'; return defined eval { $_[ 0] == 0 }; }
Re: Is a vble a number?
by demerphq (Chancellor) on Oct 23, 2003 at 12:33 UTC

    Really depends on how you define a number. If you want perls definition then use Scalar::Util's looks_like_number() otherwise use one of the regex solutions mentioned already.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi