Keep It Simple, Stupid | |
PerlMonks |
Re: Automating dispatch tablesby davido (Cardinal) |
on Apr 16, 2004 at 07:58 UTC ( [id://345673]=note: print w/replies, xml ) | Need Help?? |
I'm not an expert on any of this, but I'll accept your invitation to meditate out loud.
Your second example could just as easily be written as follows:
But what your version gains is a new package namespace. This can be a convenient way of giving all of the methods in your "dispatch table" a set of common but private variables to work with. This kind of starts feeling like static variables, except that you can get at them from the outside if you know their names. On the other hand, this could be nearly as clearly accomplished by putting the sub declarations in an enclosed lexical scope that executes near the top of your script. Example:
In this case, the subs have their own lexical scope to play within. Your second method provides a package for the methods to play in. My method provides a lexical scope. You can do a lot of the same things with that, except that the lexically scoped variables aren't as easily accessible from the outside except by the subs declared within that same scope. The next issue is the convenience of a hash as a dispatch table. Hash elements can be deleted, placed into other hashes, or handed around all together using a hashref. That's a convenient entity to work with. Your second method would be that convenient if it were taken one step further, to the point that the refs were captured into a lexically scoped dispatch hash. But then you're getting into another layer of abstraction. Not a big deal. But helpful if you want the convenience that a hash-based dispatch table can give you. A final issue to consider is to weigh the ramifications of UNIVERSAL::can being mostly incompatible with AUTOLOAD. Just be careful there.
Dave
In Section
Meditations
|
|