Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

variable has numeric value?

by Anonymous Monk
on Mar 11, 2014 at 13:58 UTC ( #1077843=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to write a script that can check if a variable's value is numeric or not.
In perlfaq I came across this:
if (/\D/) { print "has nondigits\n" } if (/^\d+$/) { print "is a whole number\n" } if (/^-?\d+$/) { print "is an integer\n" } if (/^[+-]?\d+$/) { print "is a +/- integer\n" } if (/^-?\d+\.?\d*$/) { print "is a real number\n" } if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" + } if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) { print "a C float\n" }

Does this cover (i,e. exclude as wrong) examples like -.5 or 16F, etc?

Replies are listed 'Best First'.
Re: variable has numeric value?
by choroba (Chancellor) on Mar 11, 2014 at 14:05 UTC
    To test it, just copy and paste the above code to your text editor, and add the following at the beginning:
    for ('-.5', '16F') {

    and add a closing curly bracket at the end. Then try to run the resulting script and see.

    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: variable has numeric value?
by toolic (Bishop) on Mar 11, 2014 at 14:22 UTC
Re: variable has numeric value?
by hazylife (Monk) on Mar 11, 2014 at 14:22 UTC
    See strtod() in the POSIX package.
Re: variable has numeric value?
by ww (Bishop) on Mar 11, 2014 at 14:42 UTC

    If the "perlfaq" context suggests this was supposedto illusatrate how to determine the characteristics of a possible numeric var, FILE A BUG REPORT!

    BUT, are you sure that's what intended? Can you provide a link to that section of the faq?

    Questions containing the words "doesn't work (or their moral equivalent) unless accompanied by:
    1. code
    2. verbatim error and/or warning messages
    3. a coherent explanation of what "doesn't work actually means

    ... will usually get a downvote from me.

      If the "perlfaq" ... FILE A BUG REPORT!...

      Or update your perlfaq and see what the latest says before deciding to file a report :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1077843]
Approved by toolic
Front-paged by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2017-03-28 19:59 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (340 votes). Check out past polls.