開關值「曝光補償」不等於所述第二殼體的值(兩者是字符串,字符串相等在開始時使用按表莢)。
因此,當fall-through導致開關轉到第二種情況時,它只是無法匹配。由於沒有更多的情況下,它退出。
爲了說明,這段代碼將打印輸出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
}
它開始工作,就像你的代碼(第一個匹配,next
原因水落秒到第一個,第二個沒有按不匹配),並且由於存在第三種情況,並且它匹配,那麼該塊被執行。
我不完全確定你想要第二種情況如何匹配(例如在什麼邏輯下「曝光偏差值」與「曝光偏差」值相匹配) - 唯一想到的是你想要你的「字段「充當正則表達式,並且每個案例值都是與該正則表達式匹配的字符串。如果是這樣,你需要寫下如下內容,使用開關值可以作爲子程序參考的事實(不幸的是它不可能是一個正則表達式,儘管情況可以如上所見):
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";}
}
後者產生Exp
輸出。
UPDATE
基於對問題的更新信息,以最簡單的事就是指定在第二種情況下兩個字符串作爲數組引用:
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";}
}
來源
2010-06-19 02:36:53
DVK
交換機已棄用。 – Ether 2010-06-19 03:49:38
如果您使用的是perl> = 5.10,則會有一個內置的given/when結構來替代Switch模塊。你也應該考慮使用它。 – Daenyth 2010-06-19 04:02:09
只是想指出,給定/何時仍然是experinental。請使用像CODEREFs一樣的HASH。 https://stackoverflow.com/a/46077110/1336858 – 2017-09-07 17:20:24