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 =  ...

You can use indirect name lookup:

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

You can treat it as a Hash:

my $c = NATO::{$x};
  • Ah, I needed the double colon. I definitely had tried just using the NATO{$x} to no avail. Thanks for a great alternate answer (it's longer than @ugexe 's, but for situations where ::($x) won't make it obvious what's going on, Foo::{$x} will make it crystal clear. – guifa Apr 20 at 2:52
  • 3
    @guifa the trailing :: gives you the symbol table, where all the enum items reside. That's why NATO::{...} work. – moritz Apr 22 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.