http://qs1969.pair.com?node_id=788924

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

i have a object stored as $self->{obj} and i want to return a subroutine to a handler.
ContentHandler => { '/' => \&{$self->{object}->Event}, },
This is wrong code, but i am wondering how do i send it properly by reference.

thank you

Replies are listed 'Best First'.
Re: Referencing Subroutines through a package
by zwon (Abbot) on Aug 15, 2009 at 21:52 UTC

    something like this if I got the question right:

    ContentHandler => { '/' => sub { $self->{object}->Event }, },
Re: Referencing Subroutines through a package
by mzedeler (Pilgrim) on Aug 16, 2009 at 08:58 UTC

    If you want $ContentHandler->{'/'}->() to invoke the Event method on $self->{object}, you can use an anonymous subroutine like so:

    ContentHandler => { '/' => sub {return $self->{object}->Event(@_)} }

    By the way, calling an attribute object is probably a really bad idea.

Re: Referencing Subroutines through a package
by AnomalousMonk (Archbishop) on Aug 16, 2009 at 01:28 UTC

      Also (and, I think, better)

      I disagree. I think it's worse. I'll explain, but let's complete the code first.

      The solution from the first post:

      my %handlers = ( ContentHandler => { '/' => sub { $self->{object}->Event() }, #'/' => sub { $self->{object}->Event(@_) }, }, ); my $cb = $handlers{ContentHandler}; ... = $cb->(); #... = $cb->(...);

      The solution you propose:

      my %handlers = ( ContentHandler => { '/' => $self->{object}->can('Event'), }, ); my $method = $handlers{ContentHandler}; ... = $self->{object}->$method(...);

      The problem is that you're getting the method of one object and you're calling it with a different object. Bad! If they aren't different object, then you have redundant code. Bad! The following would be a better version of your solution:

      my %handlers = ( ContentHandler => { '/' => 'Event', }, ); my $method = $handlers{ContentHandler}; ... = $self->{object}->$method(...);

      This revised solution and the one from the first post are equally good.