given when default statement in perl
In Perl, the given-when
statement allows you to test a variable against multiple values and execute different blocks of code based on the value of the variable. The default
block is optional and is executed if none of the when
blocks match the variable. The syntax for given-when
with default
statement in Perl is:
given (expression) { when (value1) { # code to execute when expression is equal to value1 } when (value2) { # code to execute when expression is equal to value2 } ... default { # code to execute when expression doesn't match any when clause } }
Here's an example to demonstrate how given-when
with default
statement works:
my $fruit = "apple"; given ($fruit) { when ("apple") { print "It's an apple.\n"; } when ("banana") { print "It's a banana.\n"; } default { print "It's not an apple or a banana.\n"; } }
In this example, the given
statement takes a variable $fruit
as its argument, and the when
statements test the value of $fruit
against different strings. If $fruit
matches a string, the code inside the corresponding when
block is executed. If none of the when
blocks match, the default
block is executed.
If $fruit
were "apple"
, the output would be:
It's an apple.
If $fruit
were "banana"
, the output would be:
It's a banana.
If $fruit
were any other value, the output would be:
It's not an apple or a banana.
Note that the given-when
statement was introduced in Perl 5.10, so if you're using an older version of Perl, you won't be able to use this syntax. In older versions of Perl, you can use if-elsif-else
statements to achieve similar functionality.