if-elsif-else Statement
Let's discuss if-elsif-else statements using different examples in this lesson.
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.
$score=50; #change the value of score to see other resultsif ($score > 100){ # If score is greater than 100print "Error: the score is greater than 100!\n";}elsif ($score < 0){ # Else If score is less than 0print "Error: the score is less than 0!\n";}elsif ($score >= 50){ # Else if score is greater or equal to 50print "Pass!\n";}else{ # If none above, then score must be between 0 and 49print "Fail!\n";}
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
score
is greater than 100. -
On line 6, we check if
score
is less than 0. -
On line 9, we check if
score
is greater than or equal to 50. -
On line 12, the
else
condition will execute if all the conditions above evaluate to “false”.
Changing score values
-
If you change the
score
to “110” the output displayed would be “Error: the score is greater than 100!” -
If you change the
score
to “-20” the output displayed would be “Error: the score is less than 0!” -
If you change the
score
to “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:
$score=70; #change the value of score to see other resultsif ($score <= 100 && $score >= 50 ){ # If score is greater than 100print "Pass!\n";}elsif ($score >= 0 && $score < 50) {print "Fail!"}else{ # If none above, then score must be less than 0 or greater than 100print "Invalid!\n";}