Perl IF... ELSIF statement

Perl IF... ELSIF statement Perl conditional statement

An if statement can be followed by an optional elsif statement, followed by another else statement.

This conditional judgment statement is useful in the case of multiple conditions.

Here are a few things you need to be aware of when using if, elsif, else statements.

  • An if statement can be followed by 0 or 1 else statement, but elsif must be followed by an else statement.

  • If statements can be followed by 0 or 1 elsif statements, but they must be written before the else statement.

  • If one of the elsif executions succeeds, the other elsif and else will no longer be executed.

Grammar

The syntax format looks like this:

if(boolean_expression 1){
   # 在布尔表达式 boolean_expression 1 为 true 执行
}
elsif( boolean_expression 2){
   # 在布尔表达式 boolean_expression 2 为 true 执行
}
elsif( boolean_expression 3){
   # 在布尔表达式 boolean_expression 3 为 true 执行
}
else{
   # 布尔表达式的条件都为 false 时执行
}

Instance

#!/usr/bin/perl

$a = 100;
# 使用 == 判断两个数是否相等
if( $a  ==  20 ){
    # 条件为 true 时执行
    printf "a 的值为 20\n";
}elsif( $a ==  30 ){
    # 条件为 true 时执行
    printf "a 的值为 30\n";
}else{
    # 以上所有的条件为 false 时执行
    printf "a 的值为 $a\n";
}

The above procedure is performed and the output is:

a 的值为 100

Perl IF... ELSIF statement Perl conditional statement