2017-09-06 26 views
0

switch語句中組病例給定一個代碼如何在Perl

use Switch; 

my $var1x = "one"; 

switch ($var1x) { 
    case "one" { print "Why so small?\n"} 
    case "two" { print "Why so small?\n"} 
    case "three" { print "That is ok.\n"} 
    case "four" { print "That is ok.\n"} 
} 

我想組的類似案件的執行。任何建議如何正確寫入Perl?

+2

'情況QR/^一個| 2個\ Z /'或'情況下[QW(一二)]'=> https://metacpan.org/pod/Switch#SYNOPSIS –

+4

注意:'有無疑是嚴重的錯誤潛伏在代碼這個時髦'從https://metacpan.org/pod/Switch#BUGS – toolic

回答

4

請不要使用舊的,慢的Switch模塊。

通常通過CODEREF散列來解決。

my $var1x = "one"; 

my $is_ok  = sub { print "That is ok.\n"}; 
my $why_small = sub { print "Why so small?\n" }; 

my %switch = (
    one => $why_small, 
    two => $why_small, 
    three => $is_ok, 
    four => $is_ok, 
    ten => sub { print "Unbelievable!\n"; }, 
); 

$switch{$var1x}->();