views:

122

answers:

3

Possible Duplicate:
How do I tell if a variable has a numeric value in Perl?

I want to decide if a variable (value parsed from a string) is a number or not. How can I do that? Well, I guess /^[0-9]+$/ would work, but is there a more elegant version?

+6  A: 
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" }

taken from here: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Perl

Parkyprg
If you insist on a regex, get it from Regexp::Common :)
brian d foy
And, every one of these regexes that uses the $ anchor allows a newline at the end of the value. That's a mistake in perlfaq4 (I've now patched the docs to remove that mistake), where Rosetta Code got its example. This example, however, was to determine what sort of number it was, not that it was any sort of number.
brian d foy
+1  A: 

using regex, its good to use:

if ($var =~ /^\d+?$/) {
    // integer
}

Alternatively, you can use POSIX.

use POSIX;

if (isdigit($var)) {
    // integer
}
Ruel
This just finds digits. It misses literals that are numbers that have more than mere digits.
brian d foy
+13  A: 

You can use the looks_like_number() function from the core Scalar::Util module.
See also the question in perlfaq: How do I determine whether a scalar is a number/whole/integer/float?

eugene y
This is arguably the most correct answer, since `Scalar::Util` hooks into the Perl API to actually ask Perl whether it thinks the variable looks numeric. Thus, for the common task of avoiding 'numeric' warnings, this will always work. Of course, sometimes it's better to simply say `no warnings 'numeric';`...
Adam Bellaire