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:

Press + to interact
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 whose constant-expression matches with the expression in the given statement.

  • The default section is optional and only gets executed when none of the constant-expression matches with the expression.

The type of expression can be different from what is written in the when block, and it will only execute the default block.

Example

The example below implements given statements:

Press + to interact
$color = 'Green'; #change value of color to see output for different cases
given ($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 executed
print "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 different when 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 first when statement will execute.

  • If the value of $color is “Green”, then the body of the second when statement will execute.

  • If none of the when statements matches with the given statement, then the body of the default 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: