Given and When Statement
Let's introduce the "given" statement, its basic syntax, and how it is written with an example.
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:
given (expression){when (constant-expression) {statement; #statement(s) execute if constant-expression is true}when (constant-expression1) {statement; #statement(s) execute if constant-expression1 is true}default {statement; #the code inside default is run when no other cases match}}
-
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:
$color = 'Green'; #change value of color to see output for different casesgiven ($color) {when ('Red'){print "The color is $color";}when ('Green'){print "The color is $color";}default{ #executed if neither case 1 nor case 2 are executedprint "The color is neither 'Red' or 'Green'";}}
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: