在Perl 5中获得开关/案例的行为 [英] Obtain a switch/case behaviour in Perl 5
问题描述
在Perl 5中是否有一种巧妙的方式来进行案例或switch语句?在我看来,他们应该在版本6上添加一个开关.
Is there a neat way of making a case or switch statement in Perl 5?. It seems to me they should include a switch on version 6..
我需要在脚本中使用此控制结构,并且听说您可以导入开关模块".但是,如何在没有导入的情况下实现此目标,以最大程度地减少依赖关系并获得可移植性?
I need this control structure in a script, and I've heard you can import a "switch module". But how can I achieve it without imports to minimize dependencies and acquire portability?
推荐答案
如果您使用的是Perl 5.10,则具有 given
/when
这是一个switch语句(请注意,它不仅可以与正则表达式进行比较,还可以阅读链接的文档以了解其全部潜能):
If you are using Perl 5.10 you have given
/when
which is a switch statement (note, it can do more than compare with regexes, read the linked docs to see its full potential):
#or any of the dozen other ways to tell 5.10 to use its new features
use feature qw/switch/;
given($string) {
when (/^abc/) { $abc = 1; }
when (/^def/) { $def = 1; }
when (/^xyz/) { $xyz = 1; }
default { $nothing = 1; }
}
如果您使用的是Perl 5.8或更早版本,则必须使用if
/elsif
/else
语句:
If you are using Perl 5.8 or earlier you must make do with if
/elsif
/else
statements:
if ($string =~ /^abc/) { $abc = 1; }
elsif ($string =~ /^def/) { $def = 1; }
elsif ($string =~ /^zyz/) { $xyz = 1; }
else { $nothing = 1; }
或嵌套的条件运算符(?:
):
$string =~ /^abc/ ? $abc = 1 :
$string =~ /^def/ ? $def = 1 :
$string =~ /^xyz/ ? $xyz = 1 :
$nothing = 1;
Core Perl中有一个模块( Switch ),该模块通过源过滤器,但据我了解,它是
There is a module in Core Perl (Switch) that gives you fake switch statements via source filters, but it is my understanding that it is fragile:
use Switch;
switch ($string) {
case /^abc/ {
case /^abc/ { $abc = 1 }
case /^def/ { $def = 1 }
case /^xyz/ { $xyz = 1 }
else { $nothing = 1 }
}
或其他语法
use Switch 'Perl6';
given ($string) {
when /^abc/ { $abc = 1; }
when /^def/ { $def = 1; }
when /^xyz/ { $xyz = 1; }
default { $nothing = 1; }
}
这篇关于在Perl 5中获得开关/案例的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!