Perl UNLESS...ELSIF Statement
An unless statement can be followed by an optional elsif statement, and then another else statement.
This kind of conditional statement is very useful when there are multiple conditions.
When using the unless, elsif, and else statements, you need to note the following points.
-
An unless statement can be followed by 0 or 1 else statements, but an elsif must be followed by an else statement.
-
An unless 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:
unless(boolean_expression 1){
# Execute if boolean_expression 1 is false
}
elsif( boolean_expression 2){
# Execute if boolean_expression 2 is true
}
elsif( boolean_expression 3){
# Execute if boolean_expression 3 is true
}
else{
# Execute when no condition matches
}
Example
#!/usr/bin/perl
$a
=
20
;
Using an unless statement to test a Boolean expression
unless
(
$a
==
30
)
{
Executed when the Boolean expression is false
printf
"
The value of a is not 30
\n
"
;
}
elsif
(
$a
==
30
)
{
Executed when the Boolean expression is true
printf
"
The value of a is 30
\n
"
;
}
else
{
Executed when no condition matches
printf
"
The value of a is
$a
\n
"
;
}
Running the above program, the output is:
a 的值不为 30
Perl Conditional Statements