Perl是否有枚举类型? [英] Does Perl have an enumeration type?

查看:158
本文介绍了Perl是否有枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl是否具有符合最佳做法的枚举类型,或者更重要的是是否需要一个?

Does Perl have an enumeration type that adheres to best practices, or maybe more importantly, does it need one?

项目I我正在工作,在整个地方使用字符串表示通常使用类似C#的语言的枚举的东西。例如,我们有一组散列数组的电话号码,每组都有一个电话类型(Home,Work,Mobile等)):

The project I am working one uses strings all over the place to denote things that would typically use an Enum in a language like C#. For example, we have a set of phone numbers in an array of hashes, each associated with a phone type ("Home", "Work", "Mobile", etc.):

$phone_number->{type} = 'Home';

在这里使用一个只读变量集还是使用枚举是足够的?我在CPAN上找到了 枚举模块但似乎使用违反 Perl最佳做法之一的裸露单词。我使用只读变量的想法如下:

Would it be sufficient to use a read-only set of variables here or should an Enum be used? I've found an enum module on CPAN but it appears to use bare words which violates one of the Perl Best Practices. My thinking on using read-only variables goes something like this:

use Readonly;

Readonly my $HOME   => 'Home';
Readonly my $WORK   => 'Work';
Readonly my $MOBILE => 'Mobile';

$phone_number->{type} = $HOME;

这是一个很好的方法还是有更好的方法?

Is this a good approach or is there a better way?

推荐答案

不,没有内置的枚举构造。 Perl没有做很多严格的打字,所以我觉得实际上没有必要一个。

No, there isn't a built-in enum construct. Perl doesn't do a lot of strict typing, so I think there's actually little need for one.

在我看来, Readonly 您使用的方法是坚实的。

In my opinion, the Readonly approach you used is solid.

更传统的 常数 pragma。

There's also the more traditional constant pragma.

use constant {
    HOME   => 'Home',
    WORK   => 'Work',
    MOBILE => 'Mobile',
};

$phone_number->{type} = HOME;

在幕后,它为每个返回值的常量设置一个函数,如此。 / p>

Behind the scenes, it sets up a function for each constant that returns the value, like so.

sub HOME () { 'Home' }

我会坚持使用 Readonly ,除非您想要利用该资源,例如:

I'd stick with Readonly unless you want to take advantage of that property, for example:

package Phone::Type;

use constant {
    HOME => 'Home',
    #...
};

package main;

print Phone::Type->HOME, "\n";

这篇关于Perl是否有枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆