Ben*_*nee 4 perl switch-statement
我有一个我想测试的值($ field).阅读perl doc(http://perldoc.perl.org/Switch.html#Allowing-fall-through),并认为我已将此钉住了.似乎没有,因为如果我通过'Exposure Bias',就没有输出,尽管'Exposure Bias Value'可以正常工作.它没有抛出任何错误,所以我不知道.
use Switch;
use strict; use warnings;
my $field = 'Exposure Bias';
switch($field){
case 'Exposure Bias' {next;}
case 'Exposure Bias Value' {print "Exp: $field\n";}
}
Run Code Online (Sandbox Code Playgroud)
更新
我似乎假装错了.如果匹配任何一种情况,我想用这个开关做的是打印运行.我认为接下来会将控制权传递给下一个案例的代码,但这是我的错误.
我如何对此进行编码,以便在第一种情况匹配时第二种情况下的代码运行?
工作方案
given($field){
when(['Exposure Bias','Exposure Bias Value']){print "Exp: $field\n";}
}
Run Code Online (Sandbox Code Playgroud)
DVK关于为什么你的开关没有按预期工作的评论是正确的,但是他忽略了提及一种更好,更安全的方式来实现你的开关.
Switch是使用源过滤器构建的,已被弃用,最好避免使用.如果您正在使用Perl 5.10或更高版本,请使用given和when构建您的switch语句:
use strict;
use warnings;
use feature qw(switch);
my $field = 'Exposure Bias';
given($field) {
when ([
'Exposure Bias',
'Exposure Bias Value',
]) {
print 'Exp: ' . $field . "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅perlsyn.
切换值'Exposure Bias'不等于第二种情况的值(它们都是字符串,字符串相等根据POD开头的表使用).
因此,当跌落导致开关转到第二种情况时; 它根本无法匹配.由于没有更多的案例,它会退出.
为了说明,Second case for bias如果您运行它,此代码将打印输出:
use Switch;
use strict; use warnings;
my $field = 'Exposure Bias';
switch($field){
case 'Exposure Bias' {next;}
case 'Exposure Bias Value' {print 'Exp: ' . $field . "\n";}
case /Exposure Bias/ { print "Second case for bias\n";} # RegExp match
}
Run Code Online (Sandbox Code Playgroud)
它开始像你的代码一样工作(第一个匹配,next导致第二个匹配,第二个不匹配),因为有第三个案例,并且它匹配,那个块的块被执行.
我不完全确定你希望第二种情况如何匹配(例如,在"曝光偏差值"与"曝光偏差"值相匹配的逻辑下) - 唯一想到的是你希望你的"场"行动作为正则表达式,每个case值都是与该正则表达式匹配的字符串.如果是这样,您需要按如下方式编写它,使用切换值可以作为子例程引用的事实(不幸的是,它不能是正则表达式,尽管如上所示,情况可以如此):
use Switch;
use strict; use warnings;
my $field = sub { return $_[0] =~ /Exposure Bias/ };
switch($field){
case 'Exposure Bias' {next;}
case 'Exposure Bias Value' {print "Exp\n";}
}
Run Code Online (Sandbox Code Playgroud)
后者产生Exp输出.
UPDATE
根据问题中的更新信息,最简单的方法是在第二种情况下将两个字符串指定为arrayref:
use Switch;
use strict; use warnings;
my $field = "Exposure Bias";
switch($field){
case 'Exposure Bias' { print "First match\n"; next;}
case ['Exposure Bias Value', 'Exposure Bias'] {print "Exp: $field\n";}
}
$ perl ~/a.pl
First match
Exp: Exposure Bias
Run Code Online (Sandbox Code Playgroud)
当然,最好抽象出价值:
use Switch;
use strict; use warnings;
my $field = "Exposure Bias";
my $exp_bias = 'Exposure Bias';
switch($field){
case "$exp_bias" { print "First match\n"; next;}
case ['Exposure Bias Value', "$exp_bias" ] {print "Exp: $field\n";}
}
Run Code Online (Sandbox Code Playgroud)