在 Perl 5 中获取 switch/case 行为 [英] Obtain a switch/case behaviour in Perl 5
问题描述
在 Perl 5 中是否有一种巧妙的方式来制作 case 或 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 中获取 switch/case 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!