如何判断一个变量在 Perl 中是否有数值? [英] How do I tell if a variable has a numeric value in Perl?
本文介绍了如何判断一个变量在 Perl 中是否有数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Perl 中是否有一种简单的方法可以让我确定给定变量是否为数字?大致如下:
Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:
if (is_number($x))
{ ... }
将是理想的.在使用 -w
开关时不会引发警告的技术当然是首选.
would be ideal. A technique that won't throw warnings when the -w
switch is being used is certainly preferred.
推荐答案
使用 Scalar::Util::looks_like_number()
使用内部 Perl C API 的looks_like_number() 函数,这可能是最有效的方法来做到这一点.请注意,字符串inf"和infinity"被视为数字.
Use Scalar::Util::looks_like_number()
which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this.
Note that the strings "inf" and "infinity" are treated as numbers.
#!/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
";
}
给出这个输出:
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
另见:
- perldoc Scalar::Util
- perldoc perlapi for
looks_like_number
这篇关于如何判断一个变量在 Perl 中是否有数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文