Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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?

Comment on variable has numeric value?
Select or Download Code
Re: variable has numeric value?
by choroba (Canon) 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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2015-06-02 12:06 GMT
Find Nodes?
    Voting Booth?

    What kind of chocolate gives you the most pleasure?

    Results (85 votes), past polls