"be consistent" | |
PerlMonks |
Breadth-first method dispatchby blokhead (Monsignor) |
on Jan 30, 2004 at 20:48 UTC ( [id://325389]=CUFP: print w/replies, xml ) | Need Help?? |
Decorator(?) classes and inheritance made me wonder how tough it would be to get breadth-first method dispatch. While a truly robust solution would involve hacking internals, you can do some interesting things still in pure Perl.
If all you want is something like SUPER that acts in a breadth-first-search way, you can use something like this: (unfortunately overriding the SUPER namespace doesn't work -- it's more magical than that)
Disclaimer: All code is proof-of-concept and probably breaks in many curious cases (cyclic isa-hierarchy for one). If anyone might find this useful, I can package it up and CPAN it. Now we can achieve this: The important thing to notice is that SUPERB::bar correctly dispatches to B::bar instead of Base::Bar. Another variant on this is to have the actual @ISA hierarchy searched in a BFS way, for when you don't use SUPER -- For example, in the code above, say we removed all the subs in the "C" package (maybe we don't need to override them at all in this subclass) and still wanted to get B::bar instead of Base::bar. To do this, you have to use your own mechanism instead of Perl's @ISA hierarchy. You can use AUTOLOAD to dispatch the calls up the hierarchy however you want. The problem is that Perl won't call the subclass' AUTOLOAD if the actual method exists higher up. To get around this, you can not declare @ISA in the subclass and use a private list of isa-classes. This way, AUTOLOAD gets called right away if the method is unimplemented in the subclass. This little package provides a simple way to do it: You call it from within a package like this: use bfs_dispatch qw/base1 base2/;, with the isa information provided. So in the code example above, we'd replace: Then when we run that code, we get what we expect: There are problems with this second approach that may be obvious to you: SUPER (and SUPERB) won't work because there is no @C::ISA. Also UNIVERSAL::isa and UNIVERSAL::can will be equally confused. Thus, this is probably a very bad idea. If you want the behavior of BFS method dispatch, you are probably better off declaring all the methods in the subclass like this: Although this approach screams maintainability problems as well. blokhead
Back to
Cool Uses for Perl
|
|