我需要在perl中传回一个枚举值,我该怎么做?
从这个线程拉出来:Perl是否有枚举类型?
use strict;
use constant {
HOME => 'home',
WORK => 'work',
MOBILE => 'mobile',
};
my $phone_number->{type} = HOME;
print "Enum: ".$phone_number->{type}."\n";
Run Code Online (Sandbox Code Playgroud)
但这不应该返回索引0吗?或者我理解这个错误?
编辑:
对于枚举类型,这样的事情会更令人期待吗?
use strict;
use constant {
HOME => 0,
WORK => 1,
MOBILE => 2,
};
my $phone_number->{type} = HOME;
print "Enum: ".$phone_number->{type}."\n";
Run Code Online (Sandbox Code Playgroud)
编辑#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;
}
Run Code Online (Sandbox Code Playgroud)
常量不是枚举(在 Perl 或我知道的任何语言中)
不,因为这里您要做的是在符号表HOME中插入键和文字之间的链接,这在 perl 术语中Home也称为 a 。bareword符号表是用散列实现的,其键和它们添加的顺序没有数字等价性。
在您的示例中,您要做的是设置$perl_number->{type} = 'Home',然后打印出来$phone_number->{type}。
| 归档时间: |
|
| 查看次数: |
8919 次 |
| 最近记录: |