Given and When Statement
Explore how to use the given and when statements in Perl to manage conditional execution. Learn to compare expressions with multiple conditions and execute specific code blocks, including handling default cases when no conditions match.
We'll cover the following...
The given-when construct
Typically, this is required when different actions need to be performed based on different values of a particular expression. The basic construct of a given statement is as follows:
-
In the above code block, the expression can be a single variable or a valid combination of different variables and constants which may evaluate to a value.
-
The
constant-expressionevaluates to a value, which is compared with the expression. -
Control is transferred to the
whenblock whoseconstant-expressionmatches with the expression in thegivenstatement. -
The
defaultsection is optional and only gets executed when none of theconstant-expressionmatches with theexpression.
The type of
expressioncan be different from what is written in thewhenblock, and it will only execute thedefaultblock.
Example
The example below implements given statements:
Explanation
In the code above:
-
On line 1, the value of variable
$coloris set to “Green”. -
On line 3, the
givenstatement takes$coloras the expression and will match it with differentwhenstatements in its body. -
On line 4, the
whenstatement executes if the color passed is “Red” and it will display: “The color is Red”. -
On line 5, the
whenstatement executes if the color passed is “Green” and it will display: “The color is Green”.
We can change the value of $color in the code above to execute various given cases.
-
If the value of
$coloris “Red”, then the body of the firstwhenstatement will execute. -
If the value of
$coloris “Green”, then the body of the secondwhenstatement will execute. -
If none of the
whenstatements matches with thegivenstatement, then the body of thedefaultstatement will execute. It will print: “The color is neither ‘Red’ nor ‘Green’”.
The figure below illustrates how this process happens using a flow chart: