Perl-if-elsif-statement

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

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

*if* ステートメントの後にオプションの *elsif ... else* ステートメントを続けることができます。これは、単一のif ... elsifステートメントを使用してさまざまな条件をテストするのに非常に便利です。
*if、elsif、else* ステートメントを使用する場合、留意すべき点はほとんどありません。
  • if には0個または1個の else を含めることができ、 elsif の後に来る必要があります。
  • if には0個以上の elsif を含めることができ、 else の前に来る必要があります。
  • elsif が成功すると、残りの elsif または else はテストされません。

構文

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

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

a has a value which is 100