如何在 Perl 中检查变量是否具有数值?


假设我们在 Perl 中运行时获得一个变量,并且我们想要检查它包含的值是否为数字,那么我们可以使用本教程中所示的两种方法。我们将使用两个简单的例子来演示它是如何工作的。

示例

最基本的方法是使用lengthdo关键字,然后忽略警告。请考虑以下代码。

$x = 100;

if (length(do { no warnings "numeric"; $x & "" })){
   print "x is numeric\n";
} else {
   print "x is non-numeric\n";
}

输出

如果您在 Perl 编译器中运行上述代码,您将在终端上获得以下输出

x is numeric

示例

一旦您将变量“x”更改为非数字内容,您将在“if”条件的“else”块中获得输出。

$x = 'abc';

if (length(do { no warnings "numeric"; $x & "" })){
   print "x is numeric\n";
} else {
   print "x is non-numeric\n";
}

输出

它将产生以下输出

x is non-numeric

示例

另一种检查变量是否为数字的方法是使用“Scalar::Util::looks_like_number()”API。它使用 Perl C API 的内部“looks_like_number()”函数,这是最有效的方法。“inf”和“infinity”字符串之间没有区别。

请考虑以下代码:

use warnings;
use strict;

use Scalar::Util qw(looks_like_number);

my @randomStuff =
  qw(10 15 .25 0.005 1.4e8 delhi India tutorialsPoint inf infinity);

foreach my $randomStuff (@randomStuff) {
   print "$randomStuff is", looks_like_number($randomStuff)? ' ': ' not', " a number\n";
}

输出

如果您在 Perl 编译器中运行此代码,它将在终端上产生以下输出

10 is  a number
15 is  a number
.25 is  a number0.005 is  a number
1.4e8 is  a number
delhi is not a number
India is not a number
tutorialsPoint is not a number
inf is  a number
infinity is  a number

更新于:2022-12-26

3K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.