代码之家  ›  专栏  ›  技术社区  ›  petersohn

如何确定Perl中的变量是否为数字?[复制品]

  •  6
  • petersohn  · 技术社区  · 14 年前

    可能重复:
    How do I tell if a variable has a numeric value in Perl?

    我想决定一个变量(从字符串中解析的值)是否是数字。我该怎么做?嗯,我猜 /^[0-9]+$/ 可以,但有更优雅的版本吗?

    3 回复  |  直到 5 年前
        1
  •  20
  •   CristiC jason.zissman    14 年前
    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" }
    

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

        2
  •  24
  •   Eugene Yarmash    14 年前

    你可以使用 looks_like_number() 核心功能 Scalar::Util 模块。
    另请参见PerlFaq中的问题: How do I determine whether a scalar is a number/whole/integer/float?

        3
  •  8
  •   Eric Leschinski Mr. Napik    5 年前

    使用regex很好:

    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
    

    或者,可以使用posix。

    use POSIX;
    
    if (isdigit($var)) {
        // integer
    }