Perl switch statement
One switch
statement allows you to test when a variable is equal to multiple values. Each value is called a case, and the variable being tested will be for each switch case
check it out.
switch case
execution is based on Switch
module Switch
the module is not installed by default.
Install the Switch.pm module
Install using CPAN
Open a command window and enter cpan
command, and then enter installSwitch
command:
# cpan
cpan[1]> install Switch // install
cpan[2]> exit // exit
Ubuntu usage apt-get
installation
sudo apt-get install libswitch-perl
Grammar
The syntax format is as follows:
Grammar
Use Switch; Switch (argument) {case1 {print "number 1"} case "a" {print "string
{case [1.. 10,42] {print "Number in list"}case ( @ array) {print "Number in array"}case/ w+/
{print "Regular matching pattern"}caseqr/ w+/{
Print "regular matching pattern"} case ( % hash) {print "hash"}
case ( &sub) {print "child process"} else {print "does not match the previous condition"}}
The following is switch
rules for the statement:
Any type of
switch
scalar parameter can be used in parentheses of the statement.In a
switch
there can be any number ofcase
statement. Every one of them.case
followed by a value to be compared and a colon.The scalar
case
after the statement will match theswitch
the scalar of the statement is compared to determine whether it is equal.When the variable being tested is equal to
case
Constant time incase
The following statement will be executed until it is encounteredbreak
Statement.switch
statement can have an optionalelse
the statement is at the end, and the statement is in allcase
executed in the case of a mismatch.When matching
case
after that, it will be executedcase
statement block code, jump out after executionswitch
statement.When matching
case
later, if we need to continue with the nextcase
statement, you need to addnext
statement.
Flow chart
Example
#/ Usr/bin/perluse
Switch$ Var=10@ Array=(10,20,30);% Hash=('key1 '=>10,'key2'=>20); Switch ($var) {case10 {print "number
10 n "{case" a "{print" string
{case [1.. 10,42] {print "Number in list"} case ( @ array) {print "Number in array"} case
( % hash) {print "In hash"}else {print "No matching condition"}}
Execute the above program, and the output is as follows:
Number 10
Next let’s take a look at the use of next
example:
Example
#/ Usr/bin/perluse
Switch$ Var=10@ Array=(10,20,30);% Hash=('key1 '=>10,'key2'=>20); Switch ($var) {case10 {print "number
10 n "; next;} # Continue executing case" a "{print" string after matching
{case [1.. 10,42] {print "Number in list"} case ( @ array) {print "Number in array"} case
( % hash) {print "In hash"}else {print "No matching condition"}}
Execute the above program, and the output is as follows:
Number 10
Numbers in the list