Categories
Posts in this category
- Introduction
- Strings, Arrays, Hashes;
- Types
- Basic Control Structures
- Subroutines and Signatures
- Objects and Classes
- Contexts
- Regexes (also called "rules")
- Junctions
- Comparing and Matching
- Containers and Values
- Where we are now - an update
- Changes to Perl 5 Operators
- Laziness
- Custom Operators
- The MAIN sub
- Twigils
- Enums
- Unicode
- Scoping
- Regexes strike back
- A grammar for (pseudo) XML
- Subset Types
- The State of the implementations
- Quoting and Parsing
- The Reduction Meta Operator
- The Cross Meta Operator
- Exceptions and control exceptions
- Common Perl 6 data processing idioms
- Currying
Thu, 27 Nov 2008
Enums
Permanent link
NAME
"Perl 5 to 6" Lesson 16 - Enums
SYNOPSIS
enum Bool <False True>; my $value = $arbitrary_value but True; if $value { say "Yes, it's true"; # will be printed } enum Day ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); if custom_get_date().Day == Day::Sat | Day::Sun { say "Weekend"; }
DESCRIPTION
Enums are versatile beasts. They are low-level classes that consist of an enumeration of constants, typically integers or strings (but can be arbitrary).
These constants can act as subtypes, methods or normal values. They can be attached to an object with the but
operator, which "mixes" the enum into the value:
my $x = $today but Day::Tue;
You can also use the type name of the Enum as a function, and supply the value as an argument:
$x = $today but Day($weekday);
Afterwards that object has a method with the name of the enum type, here Day
:
say $x.Day; # 1
The value of first constant is 0, the next 1 and so on, unless you explicitly provide another value with pair notation:
enum Hackers (:Larry<Perl>, :Guido<Python>, :Paul<Lisp>);
You can check if a specific value was mixed in by using the versatile smart match operator, or with .does
:
if $today ~~ Day::Fri { say "Thank Christ it's Friday" } if $today.does(Fri) { ... }
Note that you can specify the name of the value only (like Fri
) if that's unambiguous, if it's ambiguous you have to provide the full name Day::Fri
.
MOTIVATION
Enums replace both the "magic" that is involved with tainted variables in Perl 5 and the return "0 but True"
hack (a special case for which no warning is emitted if used as a number). Plus they give a Bool
type.
Enums also provide the power and flexibility of attaching arbitrary meta data for debugging or tracing.