I've been working with a module that has a number of helper classes. At one point, there needs to be a mapping between some string and a classname so that the appropriate helper class can be instantiated. Ok, so I create a file-global hash (all the classes are in the same file) and use it.

But, that struck me as inelegant. The number of classes is going to be relatively static, so that's not a problem. But, I still have to add a class, then add its string and classname up top.

I thought of using a Factory, but the factory would still need this list somehow. So, I thought about having each class register with the factory as it is compiled, maybe in some sort of BEGIN statement. But, that struck me as unnecessary perl-fu.

Am I just being fussy?

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Replies are listed 'Best First'.
Re: Object factories
by Aristotle (Chancellor) on Jan 15, 2003 at 22:41 UTC
    You might give them all a common package prefix and put the mapped name in a package variable. You can then grep that prefix package's symbol table. Consider:
    #!/usr/bin/perl -w package Helper::X; { no warnings 'once'; $ACTION = 'foo'; } package Helper::Y; { no warnings 'once'; $ACTION = 'bar'; } package Helper::Z; { no warnings 'once'; $ACTION = 'baz'; } package main; use strict; print map ${$Helper::{$_}->{ACTION}} . " => Helper::$_\n", grep /::\z/, keys %Helper::; __END__ baz => Helper::Z:: foo => Helper::X:: bar => Helper::Y::
    Update: added Helper:: to the output. Note: be sure, of course, not to put any packages that don't contain a helper class under the Helper:: namespace.

    Makeshifts last the longest.

Re: Object factories
by tall_man (Parson) on Jan 15, 2003 at 22:26 UTC

    It's reasonable to provide static methods in a Factory class that will let you register new classes by name. For example, see the Class::Factory module on CPAN. Then you can provide access to classes that are in files outside of your main file, and you don't have to expose a global variable.