Perl UNLESS...ELSIF 語句



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

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

  • 一個 unless 可以有零個或一個 else,並且它必須放在任何 elsif 之後。

  • 一個 unless 可以有零到多個 elsif,並且它們必須放在 else 之前。

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

語法

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

unless(boolean_expression 1) {
   # Executes when the boolean expression 1 is false
} 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 met
}

示例

#!/usr/local/bin/perl
 
$a = 20;
# check the boolean condition using if statement
unless( $a  ==  30 ) {
   # if condition is false then print the following
   printf "a has a value which is not 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 met
   printf "a has a value which is $a\n";
}

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

a has a value which is not 20
perl_conditions.htm
廣告

© . All rights reserved.