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.
Syntax:
given(expression)
{
when(value1) {Statement;}
when(value2) {given(expression)
{
when(value3) {Statement;}
when(value4) {Statement;}
when(value5) {Statement;}
default{# Code if no other case matches}
}
}
when(value6) {Statement;}
default {# Code if no other case matches}
}
Following is an example for Nested given-when statement:
use 5.010;
print "Enter a day-code between 0-6\n";
chomp(my $day_code = <>);
given ($day_code)
{
when ('0') { print 'Sunday' ;}
when ('1') { print "What time of day is it?\n";
chomp(my $day_time = <>);
given($day_time)
{
when('Morning') {print 'It is Monday Morning'};
when('Noon') {print 'It is Monday noon'};
when('Evening') {print 'It is Monday Evening'};
default{print'Invalid Input'};
}
}
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';}
}
|
Input:
1
Morning
Output:
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.
Please Login to comment...