given-when statements also use two other keywords along with it, namely break and continue. These keywords maintain the flow of the program and help in getting out of the program execution or skipping execution at a particular value.

break: break keyword is used to break out of a when block. In Perl, there is no need to explicitly write the break after every when block. It is already defined implicitly.continue: continue, on the other hand, moves to the next when block if first when block is correct.

In a given-when statement, a conditional statement must not repeat in multiple when statements, this is because Perl checks for the first occurrence of that condition only and the next repeating statements will be ignored. Also, a default statement must be placed after all the when statements because the compiler checks for condition matching with every when statement in order, and if we will place default in between, then it will take a break over there and will print the default statement.

Example:

filter_none

editclose

play_arrow

linkbrightness_4code

#!/usr/bin/perl

# Perl program to print respective day

# for the day-code using given-when statement

use5.010;

# Asking the user to provide day-code

print"Enter a day-code between 0-6\n";

# Removing newline using chomp

chomp(my$day_code= <>);

# Using given-when statement

given($day_code)

{

when('0') { print'Sunday';}

when('1') { print'Monday';}

when('2') { print'Tuesday';}

when('3') { print'Wednesday';}

when('4') { print'Thursday';}

when('5') { print'Friday';}

when('6') { print'Saturday';}

default{ print'Invalid day-code';}

}

chevron_right

filter_none

Input:

4

Output:

Enter a day-code between 0-6
Thursday

Nested given-when statement

Nested given-when statement refers to given-when statements inside of another given-when Statements. This can be used to maintain a hierarchy of inputs provided by the user for a specific output set.

Enter a day-code between 0-6
What time of day is it?
It is Monday Morning

Input:

3

Output:

Enter a day-code between 0-6
Wednesday

In the above-given Example, when the Input day-code is anything but 1 then the code will not go into the nested given-when block and the output will be same as in the previous example, but if we give 1 as Input then it will execute the Nested given-when block and the output will vary from the previous example.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.