Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an enum type in Perl?

Tags:

enums

perl

I need to pass back a enum value in perl, how can I do this?

pulling from this thread: 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;
}
like image 755
Phill Pafford Avatar asked Oct 15 '22 10:10

Phill Pafford


1 Answers

A constant is not an enum (in perl, or any language I know of)

No, because here what you're doing is inserting in the symbol table a link between the key HOME and the literal Home, this is also called a bareword in perl parlance. The symbol table is implemented with a hash, and there is no number equivalence of its keys and the order they were added.

In your example what you're doing is setting $perl_number->{type} = 'Home', and then printing out $phone_number->{type}.

like image 119
NO WAR WITH RUSSIA Avatar answered Oct 20 '22 18:10

NO WAR WITH RUSSIA