Perl switch Statement
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:
The parentheses in the switch statement can contain any scalar argument.
There can be any number of case statements within a switch. Each case is followed by the value to compare and a colon.
The scalar following the case statement is compared with the scalar in the switch statement to determine equality.
When the variable being tested equals the constant in the case, the statements following that case will be executed until a break statement is encountered.
The switch statement can have an optional else, which is executed if none of the cases match.
Once a match is found, the corresponding case block is executed and then exits the switch statement.
If we need to continue executing the next case statements after a match, we should add a next 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