user0721090601
user0721090601

Reputation: 5346

Creating an enum from its name not value

Given the enumeration

enum NATO (:alpha<A>, :bravo<B>, :charlie<C>, :delta<D>);

it's possible to easily set a variable by literally typing one of the names, or by passing one of the values to the enum object:

my $a = alpha;
my $b = NATO('B');

say $a;        # ↪︎ alpha
say $b;        # ↪︎ bravo
say $a.value;  # ↪︎ A
say $b.value;  # ↪︎ B

Besides using EVAL and given a Str that corresponds to one of the enums, how could I create $c to be an enum value equivalent to charlie?

my $x = 'charlie';
my $c =  ...

Upvotes: 12

Views: 412

Answers (2)

Curt Tilmes
Curt Tilmes

Reputation: 3045

You can treat it as a Hash:

my $c = NATO::{$x};

Upvotes: 13

ugexe
ugexe

Reputation: 5726

You can use indirect name lookup:

enum NATO (:alpha<A>, :bravo<B>, :charlie<C>);
my $x = 'charlie';
my $c = ::($x);
say $c.value;

Upvotes: 8

Related Questions