Types, classes & roles

Enums with explicit values

Full

Assign chosen underlying values to enum names instead of the 0,1,2 default.

Beyond the counting-from-zero default (Enums), an enum can pin each name to a chosen value with a list of pairs — ideal for codes like HTTP statuses or bit flags.

Assigning values #

enum HttpStatus (OK => 200, NotFound => 404);
say OK;
say OK.value;
say NotFound.value;
Output
OK
200
404

OK stringifies to its name but carries 200 as its value — so it reads well and compares numerically.

Comparing and listing #

An enum value compares against its underlying number, and .enums gives back the whole name-to-value map.

enum HttpStatus (OK => 200, NotFound => 404);
my $code = 404;
say $code == NotFound;
say HttpStatus.enums.sort;
Output
True
(NotFound => 404 OK => 200)

Notes #