I would suggest something along the following..
I took references to the methods using can (since I cannot think off the top of my head how to do it otherwise...). It is MUCH better to use code refs than do symbol table lookups on strings... but to do a successful symbol table lookup you would dopackage FOO; sub first { print "This is first\n"; } sub second { print "This is second\n"; } sub dispatch { my $self = shift; no strict 'refs'; my $command = shift; print "In dispatch, command = $command\n"; &{$self->{dispatch}{$command}}(); } sub new { my $class = shift; my $self = {}; bless $self, $class; $self->{dispatch} = { 'a'=> $self->can('first'), 'b'=> $self->can('s +econd') }; return $self; } package ::; my $foo = new FOO(); $foo->dispatch('a'); $foo->dispatch('b');
I also move the definition of your dispatch table into the new method, since you should only have to generate this once....$self->$command();
- Ant
- Some of my best work - Fish Dinner
In reply to Re: Dispatching Method Objects
by suaveant
in thread Dispatching Method Objects
by ehdonhon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |