Perl-unless-elsif-statement

提供:Dev Guides
移動先:案内検索

Perl UNLESS …​ ELSIFステートメント

*unless* ステートメントの後にオプションの *elsif ... else* ステートメントを続けることができます。これは、単一のexcept ... elsifステートメントを使用してさまざまな条件をテストするのに非常に便利です。

except、elsif、elseステートメントを使用する場合、留意すべき点はほとんどありません。

  • unless にはゼロまたは1つの else を含めることができ、 elsif の後に来る必要があります。
  • unless には、ゼロから多数の elsif を含めることができ、 else の前に来る必要があります。
  • elsif が成功すると、残りの elsif または else はテストされません。

構文

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";
}

ここでは、2つのオペランドが等しいかどうかを確認するために使用される等値演算子==を使用しています。 両方のオペランドが同じ場合はtrueを返し、そうでない場合はfalseを再実行します。 上記のコードが実行されると、次の結果が生成されます-

a has a value which is not 20