Latest web development tutorials

Perl IF ... ELSIF statements

Perl conditional statements Perl conditional statements

After a if statement with an optional elsif statement, and then followed by another else statement.

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

In use if, elsif, else statement when you need to pay attention to the following points.

  • After the if statement can keep up with 0 or an else statement, but there must be behind elsif else statements.

  • After the if statement can keep up with 0 or 1 elsif statement, but they must be written before the else statement.

  • If one elsif executed successfully, and other elsif else will no longer be executed.

grammar

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

Examples

#!/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 program, the output is:

a 的值为 100

Perl conditional statements Perl conditional statements