Latest web development tutorials

Perl switch statement

Perl conditional statements Perl conditional statements

Test case aswitch statement allows a variable equal to the multiple value.Each value is called a case, and the variable will be tested eachswitch case to be checked.

Switch Executive switch case is based on the module, Switchmodule usesFilter :: Util :: CallandText :: Balancedto perform, both modules need to be installed.

grammar

The syntax is as follows:

use Switch;

switch(argument){
   case 1            { print "数字 1" }
   case "a"          { print "字符串 a" }
   case [1..10,42]   { print "数字在列表中" }
   case (\@array)    { print "数字在数组中" }
   case /\w+/        { print "正则匹配模式" }
   case qr/\w+/      { print "正则匹配模式" }
   case (\%hash)     { print "哈希" }
   case (\&sub)      { print "子进程" }
   else              { print "不匹配之前的条件" }
}

The following are the rules of the switch statement:

  • bracketsswitch statement can be used in any type of scalar parameters.
  • In a switch you can have any number of case statements. Each case is followed by a value to compare with a colon.

  • Scalar case statement, then the scalar will switch statement, and determines whether or not the same.

  • When the variable being tested is equal to the case of constant time, followed by a case statement will be executed, until it encounters abreak statement.

  • switch statement can have an optional else,the statement in the final surface, the statement is executed in the case does not match any case.

  • When the matching case, case statement block executes code out of the switch statement after executing.

  • When the matching case, if we need to continue to execute the next case statement, you need to add thenext statement.

flow chart

Examples

#!/usr/bin/perl

use Switch;

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

switch($var){
   case 10           { print "数字 10\n" }
   case "a"          { print "字符串 a" }
   case [1..10,42]   { print "数字在列表中" }
   case (\@array)    { print "数字在数组中" }
   case (\%hash)     { print "在哈希中" }
   else              { print "没有匹配的条件" }
}

The above program, the output is:

数字 10

Next we look at the use ofnext instance:

#!/usr/bin/perl

use Switch;

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

switch($var){
   case 10           { print "数字 10\n"; next; }  # 匹配后继续执行
   case "a"          { print "string a" }
   case [1..10,42]   { print "数字在列表中" }
   case (\@array)    { print "数字在数组中" }
   case (\%hash)     { print "在哈希中" }
   else              { print "没有匹配的条件" }
}

The above program, the output is:

数字 10
数字在列表中

Perl conditional statements Perl conditional statements