2010-06-19 77 views
4

我有一個值($字段),我想測試。閱讀perl文檔(http://perldoc.perl.org/Switch.html#Allowing-fall-through),並認爲我有這個釘。似乎沒有,因爲如果我通過'曝光偏差',沒有輸出,雖然'曝光偏差值'按照它應該的那樣工作。它不會拋出任何錯誤,所以我不知道。Perl開關沒有正確地通過?

use Switch; 
use strict; use warnings; 

my $field = 'Exposure Bias'; 

switch($field){ 
    case 'Exposure Bias' {next;} 
    case 'Exposure Bias Value' {print "Exp: $field\n";} 
} 

更新

我假設它似乎是錯誤的事情。如果任何一種情況相匹配,我想用這個開關做的事情就是打印。我認爲下一個會將控制權交給下一個案例的代碼,但這是我的錯誤。

如何對代碼進行編碼以便第二種情況下的代碼在第一種情況下匹配時運行?


工作溶液

given($field){ 
    when(['Exposure Bias','Exposure Bias Value']){print "Exp: $field\n";} 
} 
+4

交換機已棄用。 – Ether 2010-06-19 03:49:38

+1

如果您使用的是perl> = 5.10,則會有一個內置的given/when結構來替代Switch模塊。你也應該考慮使用它。 – Daenyth 2010-06-19 04:02:09

+0

只是想指出,給定/何時仍然是experinental。請使用像CODEREFs一樣的HASH。 https://stackoverflow.com/a/46077110/1336858 – 2017-09-07 17:20:24

回答

7

DVK關於您的交換機爲什麼沒有按預期工作的評論是正確的,但他忽略了提供一種更好,更安全的方式來實現您的交換機。

Switch使用source filtershas been deprecated構建,最好避免。如果你是用Perl 5.10或更新工作,使用givenwhen建立自己的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"; 
    } 
} 

更多信息,請參見perlsyn

5

開關值「曝光補償」不等於所述第二殼體的值(兩者是字符串,字符串相等在開始時使用按表莢)。

因此,當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";} 
} 
+0

+1 - 這是確認工作 – 2010-06-19 02:41:43

+0

看來我對這個用法做了不正確的假設,所以我正在澄清這個問題。請參閱編輯。 – 2010-06-19 02:54:58

+0

@Ben - 看看更新是否適合你...不一定是最好的解決方案,但它的工作原理如你所願我認爲 – DVK 2010-06-19 03:17:39