Perl UNLESS...ELSIF Statement
An unless statement can be followed by an optional elsif statement, and then another else statement.
This type of conditional statement is very useful in cases with multiple conditions.
When using unless, elsif, and else statements, you need to keep the following points in mind:
- An unless statement can be followed by 0 or 1 else statement, but an 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 conditions is met, the other elsif and else statements will not be executed.
Syntax
The syntax is as follows:
unless(boolean_expression 1){
# Execute when boolean_expression 1 is false
}
elsif(boolean_expression 2){
# Execute when boolean_expression 2 is true
}
elsif(boolean_expression 3){
# Execute when boolean_expression 3 is true
}
else{
# Execute when no condition is matched
}
Example
#!/usr/bin/perl
$a = 20;
# Using unless statement to check the boolean expression
unless( $a == 30 ){
# Execute when the boolean expression is false
printf "a is not 30\n";
}elsif( $a == 30 ){
# Execute when the boolean expression is true
printf "a is 30\n";
}else{
# Execute when no condition is matched
printf "a is $a\n";
}
Executing the above program will output:
a is not 30