I need to pass back a enum value in perl, how can I do this?
pulling from this thread: http://stackoverflow.com/questions/473666/does-perl-have-an-enumeration-type
use strict;
use constant {
HOME => 'home',
WORK => 'work',
MOBILE => 'mobile',
};
my $phone_number->{type} = HOME;
print "Enum: ".$phone_number->{type}."\n";
but shouldn't this return index 0? or am I understanding this wrong?
EDIT:
So would something like this be more expectable for a enum type?
use strict;
use constant {
HOME => 0,
WORK => 1,
MOBILE => 2,
};
my $phone_number->{type} = HOME;
print "Enum: ".$phone_number->{type}."\n";
EDIT #2
Also I would like to validate on the option selected but pass back the Word rather then the Value. How can I have the best of both examples?
@VALUES = (undef, "home", "work", "mobile");
sub setValue {
if (@_ == 1) {
# we're being set
my $var = shift;
# validate the argument
my $success = _validate_constant($var, \@VALUES);
if ($success == 1) {
print "Yeah\n";
} else {
die "You must set a value to one of the following: " . join(", ", @VALUES) . "\n";
}
}
}
sub _validate_constant {
# first argument is constant
my $var = shift();
# second argument is reference to array
my @opts = @{ shift() };
my $success = 0;
foreach my $opt (@opts) {
# return true
return 1 if (defined($var) && defined($opt) && $var eq $opt);
}
# return false
return 0;
}