http://qs321.pair.com?node_id=695778

dhosek has asked for the wisdom of the Perl Monks concerning the following question:

I've got some code which uses something along the lines of
$dispatcher{$code}->($self, $parameter)
where each element of the %dispatcher hash is an anonymous subroutine which handles dealing with the various possibilities for $code.

The problem comes in where I'm realizing that what I'm frequently writing entries that look like:

foo => sub {$self = shift; $self->set_foo(shift); },
Obviously, I should be able to replace the anonymous subroutine with a straight reference to set_foo. The catch comes in that I can't seem to find the right formulation of the reference. In this case, set_foo is generated on a field in the parent class using Object::InsideOut. Any ideas on what the correct syntax should be at referencing the setter?

Replies are listed 'Best First'.
Re: Reference to a method within Object::InsideOut/parent class
by friedo (Prior) on Jul 06, 2008 at 04:41 UTC

    Obviously, I should be able to replace the anonymous subroutine with a straight reference to set_foo.

    But then you wouldn't have the object to call set_foo upon. If that's desirable (e.g. set_foo is a class method) then you can reference it with \&Fooclass::set_foo. But it sounds like it's an object method, so you'll need the object to call it on.

    If you have the object available outside of your dispatcher's anon subs, then you can just use the actual method name:

    my %dispatcher = ( foo => 'set_foo', bar => 'set_bar' ); my $method = $dispatcher{$code}; $self->$method( $parameter );
      Yeah, I supose what I can do is have two hashes, since I also need to do some more complicated processing for some of the dispatches.
Re: Reference to a method within Object::InsideOut/parent class
by alexm (Chaplain) on Jul 06, 2008 at 17:49 UTC
    Obviously, I should be able to replace the anonymous subroutine with a straight reference to set_foo.
    IIRC, using references to object methods conflicts with inheritance, so friedo's suggestion seems the way to go.