Perl IF 語句



Perl 的if語句由一個布林表示式和一個或多個語句組成。

語法

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

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

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

數字 0,字串 '0' 和 "",空列表 () 和 undef 在布林上下文中都為false,所有其他值都為true。使用!not對真值進行否定將返回一個特殊的假值。

流程圖

Perl if Statement

示例

#!/usr/local/bin/perl
 
$a = 10;
# 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";
}
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";
}
print "value of a is : $a\n";

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

a is less than 20
value of a is : 10
value of a is : 
perl_conditions.htm
廣告