NAME

Class::Constant - Build constant classes

SYNOPSIS

use Class::Constant NORTH, SOUTH, EAST, WEST;

use Class::Constant
    NORTH => "north",
    SOUTH => "south",
    EAST  => "east",
    WEST  => "west;

use Class::Constant
    NORTH => { x =>  0, y => -1 },
    SOUTH => { x =>  0, y =>  1 },
    EAST  => { x => -1, y =>  0 },
    WEST  => { x =>  1, y =>  0 };

use Class::Constant
    NORTH => "north",
             { x =>  0, y => -1 },
    SOUTH => "south",
             { x =>  0, y =>  1 },
    EAST  => "east",
             { x => -1, y =>  0 },
    WEST  => "west",
             { x =>  1, y =>  0 };

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

You can also associate named values with a constant by using a hashref:

use Class::Constant
    NORTH => { x =>  0, y => -1 },
    SOUTH => { x =>  0, y =>  1 },
    EAST  => { x => -1, y =>  0 },
    WEST  => { x =>  1, y =>  0 };

...

print "About to move ".
      $facing->x." in x and ".
      $facing->y." in y.";

And of course, you can do both:

use Class::Constant
    NORTH => "north",
             { x =>  0, y => -1 },
    SOUTH => "south",
             { x =>  0, y =>  1 },
    EAST  => "east",
             { x => -1, y =>  0 },
    WEST  => "west",
             { x =>  1, y =>  0 };

...

print "Moving $facing will move you ".
      $facing->x." in x and ".
      $facing->y." in y.";

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.