【发布时间】:2011-04-17 18:14:03
【问题描述】:
可能重复:
How do I tell if a variable has a numeric value in Perl?
我想确定一个变量(从字符串解析的值)是否为数字。我怎样才能做到这一点?好吧,我想/^[0-9]+$/ 会起作用,但有更优雅的版本吗?
【问题讨论】:
可能重复:
How do I tell if a variable has a numeric value in Perl?
我想确定一个变量(从字符串解析的值)是否为数字。我怎样才能做到这一点?好吧,我想/^[0-9]+$/ 会起作用,但有更优雅的版本吗?
【问题讨论】:
您可以使用核心Scalar::Util 模块中的looks_like_number() 函数。
另请参阅 perlfaq 中的问题:How do I determine whether a scalar is a number/whole/integer/float?
【讨论】:
Scalar::Util 挂钩到 Perl API 以实际询问 Perl 它是否认为变量看起来是数字的。因此,对于避免“数字”警告的常见任务,这将始终有效。当然,有时最好直接说no warnings 'numeric';...
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
【讨论】:
使用正则表达式,很好用:
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
}
【讨论】: