Perl IF...ELSIF 語句



一個if語句後面可以跟一個可選的elsif...else語句,這對於使用單個if...elsif語句測試各種條件非常有用。

使用if, elsif, else語句時,需要注意以下幾點。

  • 一個if語句可以有零個或一個else,並且它必須位於任何elsif之後。

  • 一個if語句可以有零個或多個elsif,並且它們必須位於else之前。

  • 一旦elsif成功,就不會測試任何剩餘的elsifelse

語法

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

if(boolean_expression 1) {
   # Executes when the boolean expression 1 is true
} elsif( boolean_expression 2) {
   # Executes when the boolean expression 2 is true
} elsif( boolean_expression 3) {
   # Executes when the boolean expression 3 is true
} else {
   # Executes when the none of the above condition is true
}

示例

#!/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 has a value which is 20\n";
} elsif( $a ==  30 ) {
   # if condition is true then print the following
   printf "a has a value which is 30\n";
} else {
   # if none of the above conditions is true
   printf "a has a value which is $a\n";
}

這裡我們使用了等號運算子 ==,用於檢查兩個運算元是否相等。如果兩個運算元相同,則返回true,否則返回false。執行上述程式碼後,將產生以下結果:

a has a value which is 100
perl_conditions.htm
廣告
© . All rights reserved.