How can I validate enum types as Perl subroutine arguments?

enums, perl, subroutine, validation

Solution

Here is one way:

#!/usr/bin/perl

package Phone::Type;

use strict;
use warnings;

use constant {
    HOME => 'Home',
    WORK => 'Work',
};

package main;

use strict;
use warnings;

sub fun {
    my ($phone_type) = @_;
    Phone::Type->can( $phone_type )
        or die "'$phone_type' is not valid\n";
}

fun('HOME'); # valid
fun('WORK'); # valid
fun('DOG');  # run-time or compile time error
__END__

C:\Temp> dfg
'DOG' is not valid

Problem

Building off Does Perl have an enumeration type?, how can I perform dynamic type checking (or static type checking if use strict is able to do so) that my subroutine argument is getting the right type of enum? ``` package Phone::Type; use constant { HOME => 'Home', WORK => 'Work', }; package main; sub fun { my ($my_phone_type_enum) = @_; # How to check my_phone_type_enum, is either Phone::Type->HOME or Phone::Type->WORK or ... but not 'Dog' or 'Cat'? } fun(Phone::Type->HOME); # valid fun(Phone::Type->WORK); # valid fun('DOG'); # run-time or compile time error ```

Original source

Related problems