Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Perl switch Statement

Perl switch Statement

Perl Conditional Statements Perl Conditional Statements

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

{

print

"

Digit 1

"

}

case

"

a

"

{

print

"

String a

"

}

case

[

1

.

.10

,

42

]

{

print

"

Number in a list

"

}

case

(

\

@array

)

{

print

"

Number in an array

"

}

case

/

\w+

/

{

print

"

Regex match pattern

"

}

case

qr

/\w+/ { p

r

int

"

Regex match pattern

"

}

case

(

\

%hash

)

{

print

"

Hash

"

}

case

(

&

sub

)

{

print

"

Subprocess

"

}

else

{

print

"

Does not match the previous conditions

"

}

}

The following are the rules of 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

"

The number 10

\n

"

}

case

"

a

"

{

print

"

String a

"

}

case

[

1

.

.10

,

42

]

{

print

"

Number in a list

"

}

case

(

\

@array

)

{

print

"

Number in an array

"

}

case

(

\

%hash

)

{

print

"

In a hash

"

}

else

{

print

"

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

{

print

"

The number 10

\n

"

;

next

;

}

Continue executing after a match

case

"

a

"

{

print

"

string a

"

}

case

[

1

.

.10

,

42

]

{

print

"

Number in a list

"

}

case

(

\

@array

)

{

print

"

Number in an array

"

}

case

(

\

%hash

)

{

print

"

In a hash

"

}

else

{

print

"

No matching condition

"

}

}

Running the above program, the output is:



数字 10

数字在列表中

Perl Conditional Statements Perl Conditional Statements