本文介绍了在 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.
推荐答案Use Scalar::Util::looks_like_number() 它使用内部 Perl C API 的 look_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 标量::Util
- perldoc perlapi looks_like_number
更多推荐
在 Perl 中,如何判断变量是否具有数值?
发布评论