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