Idiom #295 String to Enum
Given the enumerated type T, create a function TryStrToEnum that takes a string s as input and converts it into an enum value of type T.
Explain whether the conversion is case sensitive or not.
Explain what happens if the conversion fails.
use constant { RED => 1, GREEN => 2, BLUE => 3 };
sub TryStrToEnum { eval uc shift }
say GREEN; # prints 2
say TryStrToEnum('BLUE'); # prints 3
Perl is not a strictly typed language and has no builtin enum. The nearest equivalent is 'use constant', which can be used to define names that can be used like constants. Under the covers they are actually subroutines which return the associated value. There are also CPAN routines (like 'enum') which provide more flexibility. This implementation is case insensitive, courtesy of uc (uppercase). Conversion failure returns undef.
my %T = ( RED => 1, GREEN => 2, BLUE => 3 );
sub TryStrToEnum { my $s = shift; $T{uc $s} }
print GREEN; # prints 2
print TryStrToEnum('BLUE'); prints 3
Perl is not a strictly typed language and has no builtin enum. One approach is to use a hash (similar to a Python map) -- but it won't catch a name misspelling at compile time error. See 'use constant' and CPAN's 'enum' for better options. This implementation is case insensitive, courtesy of uc (uppercase). Conversion failure returns undef.