开发者

Perl, how to determine if a variable value is a number?

开发者 https://www.devze.com 2023-02-16 01:14 出处:网络
Is there a unique method to determine if a variable value is a nu开发者_Go百科mber, Since the values could be in scientific notation as well (for example, 5.814e-10)?The core module Scalar::Util expo

Is there a unique method to determine if a variable value is a nu开发者_Go百科mber, Since the values could be in scientific notation as well (for example, 5.814e-10)?


The core module Scalar::Util exports looks_like_number(), which gives access to the underlying Perl API.

looks_like_number EXPR

Returns true if perl thinks EXPR is a number.


From 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" }

There are also some commonly used modules for the task.

Scalar::Util (distributed with 5.8) provides access to perl's internal function looks_like_number for determining whether a variable looks like a number.

Data::Types exports functions that validate data types using both the above and other regular expressions.

Thirdly, there is Regexp::Common which has regular expressions to match various types of numbers.

Those three modules are available from the CPAN


There are also String::Numeric and Regexp::Common::number .. looks handy.

String::Nummeric also has a "a comparison with Scalar::Util::looks_like_number()"


Adapted from an answer in 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 };
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号