2011-03-11 64 views
10

是否有一種獨特的方法來確定一個變量值是否爲 一個數字,因爲這些值也可以用科學計數法表示(例如5.814e-10)?Perl,如何確定一個變量值是否是一個數字?

+4

「是有獨特的方法」 - 不,這是Perl的,TMTOWTDI! :) – Quentin 2011-03-11 13:36:57

+5

可能的重複[如何判斷一個變量是否在Perl中具有數值?](http://stackoverflow.com/questions/12647/how-do-i-tell-if-a-variable-has -a-numeric-value-in-perl) – daxim 2011-03-11 13:41:32

回答

23

核心模塊Scalar::Util導出looks_like_number(),它可以訪問底層的Perl API。如果perl的認爲EXPR是一個數字

looks_like_number EXPR

返回true。

+1

謝謝!它的效果很好 – Gordon 2011-03-11 19:16:06

16

來自perlfaq4: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" } 

還有一些常用的任務模塊。

Scalar::Util(以5.8分佈)提供對perl的內部函數looks_like_number的訪問,以確定變量是否看起來像一個數字。

Data::Types導出使用上述和其他正則表達式驗證數據類型的函數。

第三,有Regexp::Common它有正則表達式來匹配各種類型的數字。

這三個模塊都可以從CPAN

0

從一個答案適應於How do I tell if a variable has a numeric value in Perl? -

for my $testable (qw(1 5.25 0.001 1.3e8 foo bar 1dd 0)) 
{ 
    printf("%10s %s a number\n", 
      $testable, 
      isa_number($testable) ? "is" : "isn't") 
} 

sub isa_number { 
    use warnings FATAL => qw/numeric/; 
    my $arg = shift; 
    return unless defined $arg; 
    eval { $arg + 0; 1 }; 
} 
+1

你的'isa_number'認爲''0''不是一個數字。 – 2011-03-11 21:17:59

+0

@ Ven'Tatsu:當然,謝謝。調整。 – Ashley 2011-03-11 21:40:24

相關問題