【问题标题】:How to group cases within a switch statement in Perl如何在 Perl 中的 switch 语句中对案例进行分组
【发布时间】:2017-09-06 12:07:39
【问题描述】:

给定一个代码

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 编写它?

【问题讨论】:

标签: string perl switch-statement


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多