Perl IF...ELSE 語句



一個 Perl if 語句可以緊隨一個可選的 else 語句,它當布林表示式為 false 時執行。

語法

Perl 程式語言中 if...else 語句的語法為 -

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

如果布林表示式計算為 true,則會執行 if 塊程式碼,否則會執行 else 塊程式碼。

數字 0、字串 '0' 和 ""、空列表 () 和 undef 在布林上下文中均為 false,所有其他值均為 true。透過 !not 求得的真值的否定結果返回一個特殊的 false 值。

流程圖

Perl if...else statement

示例

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

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

當執行以上程式碼時,會產生以下結果 -

a is greater than 20
value of a is : 100
a has a false value
value of a is : 
perl_conditions.htm
廣告
© . All rights reserved.