Perl Switch声明

sno*_*kin 16 perl case switch-statement conditional-statements

如果没有匹配的案例块,有没有办法运行代码块?例如:

switch($a) {

  case // {}
  case // {}
  ...
  # DO SOMETHING IF NONE OF THE ABOVE CASES WERE MATCHED
}
Run Code Online (Sandbox Code Playgroud)

else 不是我想要的,因为它只适用于最后一个案例块.

小智 36

如果您正在运行它,那么Perl 5.10中总会有切换.

use feature qw(switch);

given($a){
  when(1) { print 'Number one'; }
  when(2) { print 'Number two'; }
  default { print 'Everything else' }
}
Run Code Online (Sandbox Code Playgroud)


cyb*_*ard 11

请注意,use Switch在perl自己的switch语句中,任何形式都被弃用,因为它正在被替换(并在下一个perl版本中删除),正如已经回答的那样:

use feature qw(switch);

given ($x)
{
when ('case1') { print 1; }
default {print 0; }
}
Run Code Online (Sandbox Code Playgroud)

使用默认情况可以达到您想要的结果.last如果您希望在评估一个条件为true后停止评估开关,也不要忘记使用.


Swa*_*r C 6

我通常使用下面的块结构,它更简单,不需要导入任何东西.

SWITCH: {
    if($key =~ /^abc/) { $key = "key starts with abc"; last SWITCH; } # 'last' breaks the 'SWITCH' block
    if($key =~ /^def/) { $key = "key starts with def"; last SWITCH; }
    if($key =~ /^ghi/) { $key = "key starts with ghi"; last SWITCH; }   
    $key = "Default value";
}

print $key;
Run Code Online (Sandbox Code Playgroud)


Tim*_*Tim 5

else 确实是你在寻找的.

switch ( $n ) {
    case 1 { print "one\n" }
    case 2 { print "two\n" }
    else   { print "other\n" }
}
Run Code Online (Sandbox Code Playgroud)

以上将输出"other"for $n=3和"one"for $n=1.