Perl UNLESS... ELSIF statement

Perl UNLESS... ELSIF statement Perl conditional statement

An unless 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 the unless, elsif, else statements.

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

  • The unless statement can be followed by 0 or 1 elsif statement, 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:

unless(boolean_expression 1){
   # 在布尔表达式 boolean_expression 1 为 false 执行
}
elsif( boolean_expression 2){
   # 在布尔表达式 boolean_expression 2 为 true 执行
}
elsif( boolean_expression 3){
   # 在布尔表达式 boolean_expression 3 为 true 执行
}
else{
   #  没有条件匹配时执行
}

Instance

#!/usr/bin/perl

$a = 20;
# 使用 unless 语句检测布尔表达式
unless( $a  ==  30 ){
    # 布尔表达式为 false 时执行
    printf "a 的值不为 30\n";
}elsif( $a ==  30 ){
    # 布尔表达式为 true 时执行
    printf "a 的值为 30\n";
}else{
    # 没有条件匹配时执行
    printf "a  的 值为 $a\n";
}

The above procedure is performed and the output is:

a 的值不为 30

Perl UNLESS... ELSIF statement Perl conditional statement