Perl does not support the use of switch statements. A switch statement allows a variable to be tested against a set list of values. In Perl, the equivalent of the switch statement is the given-when
syntax.
We state the values as given-when
. These set values are called cases. Each case has a block of code associated with it. Given that the variable is equal to a particular case, then the associated block of code will be executed. If the variable’s value does not equate to any case, the block of code associated with default
will be executed.
given(variable) {
when (1) { print "number 1"; }
when ("a") { print "string a"; }
when [1..10,42] { print "number in list"; }
when (\@array) { print "number in list"; }
default { print "previous cases not true"; }
}
There are certain rules associated with the use of switch statements in Perl:
given
– takes one scalar argument as the switch variable.default
statement executed when none of the cases match the switch variable. This is the default case.The following code shows the use of given-when
in switch statements in Perl:
use v5.10;no warnings 'experimental';$var1 = 10;@array = (10, 20, 30);print "First switch:\n";given($var1){when (10) { print "This is the case for number 10\n"; }when ("a") { print "This is the case for string a\n"; }when ([1..10,42]) { print "This is the case for number in list\n"; }when (\@array) { print "This is the case for number in list\n"; }default { print "Default case. Previous cases not true\n"; }}$var2 = 30;print "Second switch:\n";given($var2){when (10) { print "This is the case for number 10\n"; }when ("a") { print "This is the case for string a\n"; }when ([1..10,42]) { print "This is the case for number in list\n"; }when (\@array) { print "This is the case for number in list\n"; }default { print "Default case. Previous cases not true\n"; }}$var3 = 100;print "Third switch:\n";given($var3){when (10) { print "This is the case for number 10\n"; }when ("a") { print "This is the case for string a\n"; }when ([1..10,42]) { print "This is the case for number in list\n"; }when (\@array) { print "This is the case for number in list\n"; }default { print "Default case. Previous cases not true\n"; }}
Free Resources