Easy Tutorial
❮ Perl Nested Loops Perl Database Access ❯

Perl switch Statement

Perl Conditional Statements

A switch statement allows testing a variable against multiple values. Each value is called a case, and the variable being tested is checked against each switch case.

The switch case execution is based on the Switch module, which is not installed by default.

Installing the Switch.pm Module

Using CPAN to Install

Open the command window, enter the cpan command, followed by the install Switch command:

# cpan
cpan[1]> install Switch           // Install
cpan[2]> exit                     // Exit

Installing on Ubuntu with apt-get

sudo apt-get install libswitch-perl

Syntax

The syntax format is as follows:

Syntax

use Switch;

switch(argument){
   case 1            { print "Number 1" }
   case "a"          { print "String a" }
   case [1..10,42]   { print "Number in list" }
   case (\@array)    { print "Number in array" }
   case /\w+/        { print "Regex pattern match" }
   case qr/\w+/      { print "Regex pattern match" }
   case (\%hash)     { print "Hash" }
   case (\&sub)      { print "Subroutine" }
   else              { print "No match to previous conditions" }
}

The following are the rules for the switch statement:

Flowchart

Example

#!/usr/bin/perl

use Switch;

$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);

switch($var){
   case 10           { print "Number 10\n" }
   case "a"          { print "String a" }
   case [1..10,42]   { print "Number in list" }
   case (\@array)    { print "Number in array" }
   case (\%hash)     { print "In hash" }
   else              { print "No matching condition" }
}

Executing the above program will output:

Number 10

Next, let's look at an example using next:

Example

#!/usr/bin/perl

use Switch;

$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);

switch($var){
   case 10           { print "Number 10\n"; next; }  # Continue execution after match
   case "a"          { print "string a" }
   case [1..10,42]   { print "Number in list" }
   case (\@array)    { print "Number in array" }
   case (\%hash)     { print "In hash" }
   else              { print "No matching condition" }
}

Executing the above program will output:

Number 10
Number in list

Perl Conditional Statements

❮ Perl Nested Loops Perl Database Access ❯