Does Perl have an enumeration type?

Perl does in fact have an enum type like in C. Try this for details.

perldoc enum

For instance:

use enum qw(HOME WORK MOBILE);

Now we have:

HOME == 0
WORK == 1
MOBILE == 2

You can also set the indices yourself:

use enum qw(HOME=0 WORK MOBILE=10 FAX);

Now we have:

HOME == 0
WORK == 1
MOBILE == 10
FAX == 11

Look here for more details.

Note that this isn't supported in every version of Perl. I know that v5.8.3 doesn't support it, while v5.8.7 does.


Perl doesn't support the concept natively but there are modules to add this functionality

https://metacpan.org/pod/enum


Your way is more than adequate.

You can also create enums with Moose::Util::TypeConstraints, if you happen to be using Moose. (Which you should be.)


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.

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

There's also the more traditional constant pragma.

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

$phone_number->{type} = HOME;

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

sub HOME () { 'Home' }

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

Tags:

Enums

Perl