Perl IF...ELSIF statement

Perl 条件语句Perl conditional statements

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

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

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

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

  • An if 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 statements will no longer be executed.

Syntax

The syntax format is as follows:

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 时执行
}

Example

#!/usr/bin/perl $a = 100; # Use == to determine whether two numbers are equal if( $a == 20 ){ # Execute when the condition is true printf "The value of a is 20\n"; }elsif( $a == 30 ){ # Execute when the condition is true printf "The value of a is 30\n"; }else{ # Execute when all the above conditions are false printf "The value of a is$a\n"; }

After executing the above program, the output result is:

a 的值为 100

Perl 条件语句Perl conditional statements

Other extensions