Perl除非...否則語句
Perlunless語句後面可以跟一個可選的else語句,當布林表示式為真時執行該語句。
語法
Perl程式語言中unless...else 語句的語法為:
unless(boolean_expression) {
# statement(s) will execute if the given condition is false
} else {
# statement(s) will execute if the given condition is true
}
如果布林表示式求值為真,則執行unless程式碼塊,否則執行else程式碼塊。
在布林上下文中,數字0、字串“0”和“”,空列表()和undef都是假,所有其他值都是真。透過!或not對真值進行否定會返回一個特殊的假值。
流程圖
示例
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using unless statement
unless( $a == 20 ) {
# if condition is false then print the following
printf "given condition is false\n";
} else {
# if condition is true then print the following
printf "given condition is true\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";
} else {
# if condition is true then print the following
printf "a has a true value\n";
}
print "value of a is : $a\n";
執行上述程式碼時,會生成以下結果:
given condition is false value of a is : 100 a has a false value value of a is :
perl_conditions.htm
廣告