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-expression
evaluates to a value, which is compared with the expression. -
Control is transferred to the
when
block whoseconstant-expression
matches with the expression in thegiven
statement. -
The
default
section is optional and only gets executed when none of theconstant-expression
matches with theexpression
.
The type of
expression
can be different from what is written in thewhen
block, and it will only execute thedefault
block.
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
$color
is set to “Green”. -
On line 3, the
given
statement takes$color
as the expression and will match it with differentwhen
statements in its body. -
On line 4, the
when
statement executes if the color passed is “Red” and it will display: “The color is Red”. -
On line 5, the
when
statement 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
$color
is “Red”, then the body of the firstwhen
statement will execute. -
If the value of
$color
is “Green”, then the body of the secondwhen
statement will execute. -
If none of the
when
statements matches with thegiven
statement, then the body of thedefault
statement will execute. It will print: “The color is neither ‘Red’ nor ‘Green’”.
The figure below illustrates how this process happens using a flow chart: