How do I decide if a variable is numeric in Perl?

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?


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


Using regex, it's good to use:

sub is_int { 
    $str = $_[0]; 
    #trim whitespace both sides
    $str =~ s/^\s+|\s+$//g;          

    #Alternatively, to match any float-like numeric, use:
    # m/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/

    #flatten to string and match dash or plus and one or more digits
    if ($str =~ /^(\-|\+)?\d+?$/) {
        print "yes  " . $_[0] . "\n";
    }
    else{
        print "no   " . $_[0] . "\n";
    }
}
is_int(-12345678901234);     #yes
is_int(-1);                  #yes
is_int(23.);                 #yes
is_int(-23.);                #yes
is_int(0);                   #yes
is_int(+1);                  #yes
is_int(12345678901234);      #yes
is_int("\t23");              #yes
is_int("23\t");              #yes
is_int("08");                #yes
is_int("-12345678901234");   #yes
is_int("-1");                #yes
is_int("0");                 #yes
is_int("+1");                #yes
is_int("123456789012345");   #yes
is_int("-");                 #no
is_int("+");                 #no 
is_int("yadz");              #no
is_int("");                  #no
is_int(undef);               #no
is_int("- 5");               #no
is_int("+ -5");              #no
is_int("23.1234");           #no
is_int("23.");               #no
is_int("--1");               #no
is_int("++1");               #no
is_int(" 23.5 ");            #no
is_int(".5");                #no
is_int(",5");                #no
is_int("%5");                #no
is_int("5%");                #no

Alternatively, you can use POSIX.

use POSIX;

if (isdigit($var)) {
    // integer
}