Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 638
Jim Bollinger Avatar asked Feb 10 '26 08:02

Jim Bollinger


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";
like image 122
Jonathan Worthington Avatar answered Feb 15 '26 12:02

Jonathan Worthington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!