如何在Perl中的switch语句中对案例进行分组

时间:2017-09-06 12:07:40

标签: string perl switch-statement

给出代码

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中正确编写它的任何建议吗?

1 个答案:

答案 0 :(得分:5)

请不要使用旧的慢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}->();