What are switch statements in Perl 5?

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.

Syntax

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"; }
}

Rules

There are certain rules associated with the use of switch statements in Perl:

  1. The switch statement – i.e., given – takes one scalar argument as the switch variable.
  2. The switch statement is followed by a code block that may contain one or more cases.
  3. Each case statement takes one scalar argument and checks for matching between the argument and the switch variable.
  4. If the case argument and the switch variable match, the code block associated with the case is executed.
  5. The switch statement may have an extra default statement executed when none of the cases match the switch variable. This is the default case.

Code

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

Copyright ©2025 Educative, Inc. All rights reserved