如何在 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.