在Perl中是否有一种简单的方法可以让我确定给定的变量是否为数字?有点像:
if (is_number($x))
{ ... }
Run Code Online (Sandbox Code Playgroud)
会是理想的.当使用-w开关时不会发出警告的技术当然是首选.
noh*_*hat 123
使用Scalar::Util::looks_like_number()它使用内部Perl C API的look_like_number()函数,这可能是最有效的方法.请注意,字符串"inf"和"infinity"被视为数字.
#!/usr/bin/perl
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);
foreach my $expr (@exprs) {
print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n";
}
Run Code Online (Sandbox Code Playgroud)
给出这个输出:
1 is a number
5.25 is a number
0.001 is a number
1.3e8 is a number
foo is not a number
bar is not a number
1dd is not a number
inf is a number
infinity is a number
Run Code Online (Sandbox Code Playgroud)
looks_like_numbernau*_*cho 23
查看CPAN模块Regexp :: Common.我认为它完全符合您的需要并处理所有边缘情况(例如实数,科学记数法等).例如
use Regexp::Common;
if ($var =~ /$RE{num}{real}/) { print q{a number}; }
Run Code Online (Sandbox Code Playgroud)
yst*_*sth 22
最初的问题是如何判断变量是否为数字,而不是"是否具有数值".
有一些运算符对数字和字符串操作数具有单独的操作模式,其中"数字"表示最初为数字或曾在数字上下文中使用的任何内容(例如$x = "123"; 0+$x,在添加之前,$x是字符串,之后是被认为是数字的).
一种说法是:
if ( length( do { no warnings "numeric"; $x & "" } ) ) {
print "$x is numeric\n";
}
Run Code Online (Sandbox Code Playgroud)
小智 9
这个问题的一个简单(也许是简单的)答案是$x数字的内容如下:
if ($x eq $x+0) { .... }
Run Code Online (Sandbox Code Playgroud)
它将原始文本$x与$x转换为数值进行文本比较.
通常使用正则表达式进行数字验证.此代码将确定某些内容是否为数字以及检查未定义的变量以便不抛出警告:
sub is_integer {
defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
}
sub is_float {
defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
}
Run Code Online (Sandbox Code Playgroud)
这是你应该看的一些阅读材料.