NAME
Class::Constant - Build constant classes
SYNOPSIS
DESCRIPTION
Class::Constant allows you to declaratively created so-called "constant classes" (something like "typesafe enumerations" in Java).
The simplest example of creating a constant class is like so:
package Direction;
use Class::Constant NORTH, SOUTH, EAST, WEST;
You'd might then use this in your application like so:
use Direction;
my $facing = Direction::NORTH;
...
if ($facing == Direction::SOUTH) {
move_south();
}
Each constant has an internal ordinal value. These values are unique per-package, and are generated sequentially. So in the example above, the constants would have the following ordinal values:
NORTH 0
SOUTH 1
EAST 2
WEST 3
You can get the ordinal value for a constant using the get_ordinal
method:
my $ordinal = SOUTH->get_ordinal;
Additionally, you can get a constant value back given the ordinal value using the by_ordinal
method:
my $direction = Direction->by_ordinal(2);
By default, objects stringify to their ordinal value. You set your own string for any given constant like so:
use Class::Constant
NORTH => "north",
SOUTH => "south",
EAST => "east",
WEST => "west;
...
print "You are facing $facing.\n";
AUTHOR
Robert Norris (rob@cataclysm.cx)
BUGS
This documentation probably sucks; I found it exceptionally difficult to explain what I was trying to do here.
COPYRIGHT
Copyright (c) 2006 Robert Norris. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.