Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Referencing Subroutines through a package

by zer (Deacon)
on Aug 15, 2009 at 20:29 UTC ( #788924=perlquestion: print w/replies, xml ) Need Help??

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 (Bishop) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://788924]
Approved by zwon
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2022-08-08 04:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?