加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:44:50 所属栏目:大数据 来源:网络整理
导读:我需要在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}."
我需要在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 "Yeahn";
   } 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用语中也称为裸字.符号表使用散列实现,并且没有数字等价的键和它们的添加顺序.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读