繁体   English   中英

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

[英]How can I create an enum type in Perl?

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

从这个线程拉出来: Perl是否有枚举类型?

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

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

不,因为在这里你正在做的是在符号表中插入关键HOME和文字Home之间的链接,这在perl用语中也称为bareword 符号表使用散列实现,并且没有数字等效的键和它们的添加顺序。

在你的例子中,你正在做的是设置$perl_number->{type} = 'Home' ,然后打印$phone_number->{type}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM