Perl switch Statement
A switch The statement allows testing a variable against multiple values. Each value is called a case, and the tested variable is checked against each switch case .
switch case execution is based on the Switch module, Switch which is not installed by default.
Installing the Switch.pm Module
Installing with CPAN
Open a command window, enter the cpan command, then enter the install Switch command:
# cpan
cpan[1]> install Switch // 安装
cpan[2]> 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
{
"
Digit 1
"
}
case
"
a
"
{
"
String a
"
}
case
[
1
.
.10
,
42
]
{
"
Number in a list
"
}
case
(
\
@array
)
{
"
Number in an array
"
}
case
/
\w+
/
{
"
Regex match pattern
"
}
case
qr
/\w+/ { p
r
int
"
Regex match pattern
"
}
case
(
\
%hash
)
{
"
Hash
"
}
case
(
&
sub
)
{
"
Subprocess
"
}
else
{
"
Does not match the previous conditions
"
}
}
The following are the rules of the switch statement:
- switch Any type of scalar argument can be used in the parentheses of the statement.
-
There can be any number of case statements in a switch. Each case is followed by a value to compare and a colon.
-
The scalar after a case statement is compared with the scalar of the switch statement to determine whether they are equal.
-
When the tested variable equals the constant in the case, the statements following the case are executed until break is encountered.
-
switch statement can have an optional else , this statement is at the very end; it executes when no case matches.
-
When a case matches, the code block of that case statement is executed, and after execution it breaks out of the switch statement.
-
When a case matches, if we need to continue executing the following case statements, we need to add next if statement.
Flowchart

Example
#!/usr/bin/perl
use Switch
;
$var
=
10
;
@array
=
(
10
,
20
,
30
)
;
%hash
=
(
'
key1
'
=>
10
,
'
key2
'
=>
20
)
;
switch
(
$var
)
{
case
10
{
"
The number 10
\n
"
}
case
"
a
"
{
"
String a
"
}
case
[
1
.
.10
,
42
]
{
"
Number in a list
"
}
case
(
\
@array
)
{
"
Number in an array
"
}
case
(
\
%hash
)
{
"
In a hash
"
}
else
{
"
No matching condition
"
}
}
Running the above program, the output is:
数字 10
Next, let's look at using next examples:
Example
#!/usr/bin/perl
use Switch
;
$var
=
10
;
@array
=
(
10
,
20
,
30
)
;
%hash
=
(
'
key1
'
=>
10
,
'
key2
'
=>
20
)
;
switch
(
$var
)
{
case
10
{
"
The number 10
\n
"
;
next
;
}
Continue executing after a match
case
"
a
"
{
"
string a
"
}
case
[
1
.
.10
,
42
]
{
"
Number in a list
"
}
case
(
\
@array
)
{
"
Number in an array
"
}
case
(
\
%hash
)
{
"
In a hash
"
}
else
{
"
No matching condition
"
}
}
Running the above program, the output is:
数字 10
数字在列表中
Perl Conditional Statements