if-elsif-else Statement
Explore how to implement Perl conditional statements using if, elsif, and else constructs. Learn to evaluate multiple conditions and control the execution flow based on different scenarios.
We'll cover the following...
The elsif statement
When there are different possible actions against a set of different conditions, then elsif is used to extend the if statement. The conditional block starts with an if-statement followed by multiple elsif statements, each with a different condition, and may end with an optional else-statement.
Syntax
The syntax and usage of the if-statement with the elsif statement are presented in the following example.
Explanation
-
All the statements in the code above will run in order from top to bottom until a condition has been met.
-
On line 3, we check if
scoreis greater than 100. -
On line 6, we check if
scoreis less than 0. -
On line 9, we check if
scoreis greater than or equal to 50. -
On line 12, the
elsecondition will execute if all the conditions above evaluate to “false”.
Changing score values
-
If you change the
scoreto “110” the output displayed would be “Error: the score is greater than 100!” -
If you change the
scoreto “-20” the output displayed would be “Error: the score is less than 0!” -
If you change the
scoreto “48” the output displayed would be: “Fail”
Logical operators in if condition
Logical operators can possibly be used to include multiple conditions in one if or elsif statement, as given in the following example: