如何确定Perl中的变量是否为数字?

pet*_*ohn 8 variables perl numbers

可能重复:
如何判断变量在Perl中是否具有数值?

我想确定变量(从字符串解析的值)是否为数字.我怎样才能做到这一点?好吧,我想/^[0-9]+$/会工作,但有更优雅的版本吗?

Eug*_*ash 24

您可以使用looks_like_number()核心Scalar :: Util模块中的函数.
另请参阅perlfaq中的问题:如何确定标量是否为数字/整数/整数/浮点数?

  • 这可以说是最正确的答案,因为`Scalar :: Util`挂钩到Perl API实际问Perl是否认为变量看起来是数字.因此,对于避免"数字"警告的常见任务,这将始终有效.当然,有时候最好简单地说'没有警告'数字';`... (2认同)

Cri*_*tiC 22

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" }
Run Code Online (Sandbox Code Playgroud)

取自这里:http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Perl

  • 如果你坚持正则表达式,从Regexp :: Common :)获取它 (2认同)

Rue*_*uel 9

使用正则表达式,它的好用:

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
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用POSIX.

use POSIX;

if (isdigit($var)) {
    // integer
}
Run Code Online (Sandbox Code Playgroud)