Jim Bollinger
Jim Bollinger

Reputation: 1815

How to convert Str to enum?

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?

Upvotes: 14

Views: 208

Answers (1)

Jonathan Worthington
Jonathan Worthington

Reputation: 29454

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

Upvotes: 17

Related Questions