开发者

How can I create an enum type in Perl?

开发者 https://www.devze.com 2022-12-17 21:22 出处:网络
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?

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);
开发者_Go百科
   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;
}


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}.


If you want enums, use the enum module.

0

精彩评论

暂无评论...
验证码 换一张
取 消