The Midnight clone I keep talking about (and I am getting around to writing about, really) is actually a port to Perl of a Java application. My initial goal was to get the thing working, then make it more Perl like.
One interesting pattern that is used throughout the original is special classes that act only as enumerated types - they simply create a bunch of instances of themselves with specific names that act as constants. These classes are known in Java as “typesafe enumerations”.
So I needed something to replace them with. My first attempt was to simply create empty packages with a pile of
use constant declarations in them. This worked well enough, but the original enumeration classes had additional features - they needed to stringify properly (via a
toString method), they needed to compare equal only to themselves (something
use constant can’t do, since its constants resolve to just plain scalars) and the constants can be objects with methods declared on them.
Now I don’t know if all these extras stop the classes are “correct” by some theoretical definition of what a typesafe enumeration should be (if such a definition exists), but there’s no denying that this stuff is useful, and Perl has always been about practicality over usefulness. Plus, I’ve started to think of places where I could use something similar in other code of written - pretty much anywhere that a variable could have a limited number of possible values, like state variables.
So I implemented something generic and useful, that I’m now quite proud of: Class::Constant. It makes it dead simple to declare a basic C-style enumeration, but has enough wackiness to do some really crazy things. I’ll talk a bit more about some real examples once I start writing about my project, real soon now. Until then, this is just highly ineffective advertising :)