14
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?

Jim Bollinger
  • 1,671
  • 1
  • 13
  • Does this answer your question? [Creating an enum from its name not value](https://stackoverflow.com/questions/55769656/creating-an-enum-from-its-name-not-value) – Julia Jan 24 '23 at 10:13

1 Answers1

17

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";
Jonathan Worthington
  • 29,104
  • 2
  • 97
  • 136