How to convert Str to enum?

Viewed 122
enum Colors<red green blue>

say red;  # OUTPUT: red

my $foo = "red";

my Colors $color = $foo.(...)

What code do I put in the Stub to convert the Str "red" to the Color red?

1 Answers

The enum declarator installs the elements under the Colors package as well as providing the short names, thus red can also be accessed as Colors::red. Therefore, one can use the package lookup syntax to do the job:

my Colors $color = Colors::{$foo};

Optionally providing an error or default:

my Colors $color = Colors::{$foo} // die "No such color $foo";
Related