Perl unless 語句



Perl 的 unless 語句由一個布林表示式後跟一個或多個語句組成。

語法

Perl 程式語言中 unless 語句的語法如下:

unless(boolean_expression) {
   # statement(s) will execute if the given condition is false
}

如果布林表示式計算結果為 false,則將執行 unless 語句內的程式碼塊。如果布林表示式計算結果為 true,則將執行 unless 語句結束後的第一組程式碼(在閉合花括號之後)。

數字 0、字串 '0' 和 ""、空列表 () 以及 undef 在布林上下文中都為 false,所有其他值都為 true。透過 !not 對真值取反會返回一個特殊的假值。

流程圖

Perl unless statement

示例

#!/usr/local/bin/perl
 
$a = 20;
# check the boolean condition using unless statement
unless( $a < 20 ) {
   # if condition is false then print the following
   printf "a is not less than 20\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using unless statement
unless ( $a ) {
   # if condition is false then print the following
   printf "a has a false value\n";
}
print "value of a is : $a\n";

第一個 unless 語句使用了小於運算子 (<),它比較兩個運算元,如果第一個運算元小於第二個運算元,則返回 true,否則返回 false。因此,當執行上述程式碼時,它會產生以下結果:

a is not less than 20
value of a is : 20
a has a false value
value of a is : 
perl_conditions.htm
廣告

© . All rights reserved.