Perl UNLESS...ELSIF Statement

Perl 条件语句Perl Conditional Statements

An unless statement can be followed by an optional elsif statement, and then another else statement.

This conditional statement is very useful when there are multiple conditions.

When using unless, elsif, and else statements, you need to note the following points.

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

  • An 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 statements executes successfully, the other elsif and else will not be executed.

Syntax

The syntax format is as follows:

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{
   #  没有条件匹配时执行
}

Example

#!/usr/bin/perl $a = 20; # Use the unless statement to test boolean expressions unless( $a == 30 ){ # Execute when the boolean expression is false printf "The value of a is not 30\n"; }elsif( $a == 30 ){ # Execute when the boolean expression is true printf "The value of a is 30\n"; }else{ # Execute when no condition matches printf "The value of a is$a\n"; }

Executing the above program produces the following output:

a 的值不为 30

Perl 条件语句Perl Conditional Statements

Other Extensions