Perl开关未正确断开?
我有一个要测试的值($field)。阅读perl文档(),并认为我已经解决了这个问题。似乎不是,因为如果我通过“曝光偏差”,就不会有输出,尽管“曝光偏差值”的工作原理应该是这样的。它不会出错,所以我不知道Perl开关未正确断开?,perl,switch-statement,Perl,Switch Statement,我有一个要测试的值($field)。阅读perl文档(),并认为我已经解决了这个问题。似乎不是,因为如果我通过“曝光偏差”,就不会有输出,尽管“曝光偏差值”的工作原理应该是这样的。它不会出错,所以我不知道 use Switch; use strict; use warnings; my $field = 'Exposure Bias'; switch($field){ case 'Exposure Bias' {next;} case '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";}
}
更新 看来我猜错了。我想用这个开关做的是在任何一种情况都匹配的情况下运行打印。我以为next会将控制权转移到下一个案例的代码上,但那是我的错误 如何对其进行编码,以便在第一个案例匹配的情况下运行第二个案例中的代码
工作溶液
given($field){
when(['Exposure Bias','Exposure Bias Value']){print "Exp: $field\n";}
}
开关值“曝光偏差”不等于第二种情况的值(两者都是字符串,字符串相等性按照POD开头的表格使用) 因此,当跌落导致开关转到第二种情况时;它根本不匹配。既然没有更多的案子了,它就退出了 举例来说,如果您运行此代码,它将打印偏差的第二种情况下的输出:
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
}
它开始工作时就像你的代码一样(第一个匹配,next
导致第二个失败,第二个不匹配),因为有第三种情况,并且它匹配,所以执行该块
我不完全确定您希望第二个案例如何匹配(例如,“曝光偏差值”在什么逻辑下匹配“曝光偏差”值)-唯一想到的是您希望您的“字段”充当正则表达式,并且每个案例值都是与该正则表达式匹配的字符串。如果是这样,您需要使用开关值可以是子例程引用这一事实(不幸的是,它不能是正则表达式,尽管在这种情况下可以,如上所述)编写它:
后者产生Exp
输出
更新 根据问题中更新的信息,最简单的方法是在第二种情况下将两个字符串都指定为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
当然,最好将价值抽象掉:
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";}
}
DVK关于交换机为何不能按预期工作的评论是正确的,但他忽略了提到一种更好、更安全的实现交换机的方法
开关
是使用和构建的,最好避免使用。如果您使用的是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";
}
}
有关更多信息,请参阅。我似乎对该用法做出了错误的假设,因此我澄清了这个问题。请查看编辑。@Ben-查看更新是否适合您。。。这不一定是最好的解决方案,但它可以按照您的意愿工作。我认为,如果您使用的是perl>=5.10,那么就有一个内置的given/when结构来替换开关模块。你也应该考虑使用它。只是想注意,given/when仍然是经验。请使用类似于哈希的代码引用。
use strict;
use warnings;
use feature qw(switch);
my $field = 'Exposure Bias';
given($field) {
when ([
'Exposure Bias',
'Exposure Bias Value',
]) {
print 'Exp: ' . $field . "\n";
}
}