Perl IF...ELSIF Statement
An if statement can be followed by an optional elsif statement, and then by another else statement.
This kind of conditional statement is very useful when there are multiple conditions.
When using if, elsif, and else statements, you need to pay attention to the following points.
-
An if statement can be followed by 0 or 1 else statement, but an elsif must be followed by an else statement.
-
An if statement can be followed by 0 or 1 elsif statements, but they must be written before the else statement.
-
If one of the elsif statements executes successfully, the other elsif and else statements will not be executed.
Syntax
The syntax format is as follows:
if(boolean_expression 1){
# Execute if boolean_expression 1 is true
}
elsif( boolean_expression 2){
# Execute if boolean_expression 2 is true
}
elsif( boolean_expression 3){
# Execute if boolean_expression 3 is true
}
else{
# Executes when all conditions of the boolean expression are false
}
Example
#!/usr/bin/perl
$a
=
100
;
Using == to determine whether two numbers are equal
if
(
$a
==
20
)
{
Executed when the condition is true
printf
"
The value of a is 20
\n
"
;
}
elsif
(
$a
==
30
)
{
Executed when the condition is true
printf
"
The value of a is 30
\n
"
;
}
else
{
Executed when all of the above conditions are false
printf
"
The value of a is
$a
\n
"
;
}
Running the above program, the output is:
a 的值为 100
Perl Conditional Statements