如何在Perl中创建枚举类型?

时间:2010-01-25 19:29:01

标签: perl enums

我需要在perl中传回一个枚举值,我该怎么做?

从这个帖子中拉出来: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";

但是这不应该返回索引0吗?或者我理解这个错误?

编辑:

对于枚举类型,这样的事情会更令人期待吗?

use strict;

use constant {
    HOME   => 0,
    WORK   => 1,
    MOBILE => 2,
};

my $phone_number->{type} = HOME;
print "Enum: ".$phone_number->{type}."\n";

编辑#2

此外,我想验证所选的选项,但传回Word而不是值。我怎样才能充分利用这两个例子?

@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;
}

2 个答案:

答案 0 :(得分:2)

常量不是枚举(用perl或我所知的任何语言)

不,因为您正在做的是在符号表中插入密钥HOME和文字Home之间的链接,这也称为{ {1}}用perl的说法。符号表使用散列实现,并且没有数字等价的键及其添加顺序。

在您的示例中,您正在设置bareword,然后打印$perl_number->{type} = 'Home'

答案 1 :(得分:2)

如果您需要枚举,请使用enum模块。

相关问题