kuszi
kuszi

Reputation: 2079

How to group cases within a switch statement in Perl

Given a code

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"}
}

I would like to group the implementation of similar cases. Any recommendations how to write it in Perl properly?

Upvotes: 1

Views: 789

Answers (1)

Akzhan Abdulin
Akzhan Abdulin

Reputation: 1011

Please don't use old, slow Switch module.

Usually it is resolved by CODEREF hashes.

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}->();

Upvotes: 5

Related Questions