Perl switch statement

Perl switch statement Perl conditional statement

A switch statement allows you to test when a variable is equal to more than one value. Each value is called a case, and the variable being tested checks each switch case.

Switch case execution is based on the Switch module, which is performed using Filter::Util::Call and Text::Balanced, both of which need to be installed.

Grammar

The syntax format looks like this:

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 "不匹配之前的条件" }
}

Here are the rules for the switch statement:

  • You can use any type of standard argument in the parentheses of a switch statement.
  • You can have any number of case statements in a switch. Each case is followed by a value to compare and a colon.

  • The calibration after the case statement is compared to the stum of the switch statement to determine whether it is equal.

  • When the variable being tested is equal to the constant in case, the statement followed by case is executed until a break statement is encountered.

  • The switch statement can have an optional else, which is executed at the end, and the statement executes in the event that all case mismatches.

  • When case is matched, the case statement block code is executed and the switch statement jumps out after execution.

  • When the case is matched, if we need to continue with the next case statement, we need to add the next statement.

Flow chart

Perl switch statement

Instance

#!/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 procedure is performed and the output is:

数字 10

Let's look at an example that uses next:

#!/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 procedure is performed and the output is:

数字 10
数字在列表中

Perl switch statement Perl conditional statement