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

I want to put a reference to a method of my object as a value in a hash. Here is what I've tried:
my $action = { 'dosomething' => $object->something };
I'm doing this so a user can enter a command and the object will call the method. I just want a reference to put in the hash, right? Here is the page I was on in case you are wondering: here BTW: The way I do it doesn't work, the arrow operator dereferences the method I think.

Replies are listed 'Best First'.
Re: How do I create a reference to an object method?
by kyle (Abbot) on Jun 25, 2008 at 19:31 UTC

    If you want to call the method on that particular object, I think the closure solution is best.

    my $action = { doit => sub { $object->it( @_ ) } };

    That way, you can call $action->{doit}->( ... ), and it's the same as calling $object->it( ... ). That's nice if you want to forget about the particular object.

    If you want a reference to the sub that would be called, you can use UNIVERSAL::can:

    my $action = { doit => $object->can( 'it' ) };

    In that case, you'd have a reference to the method, but the object itself is not in your hash. To call it as an instance method as above, you'd have to $action->{doit}->( $object, ... ). That's nice if you want to call it with different objects.

      To call it as an instance method as above, you'd have to $action->{doit}->( $object, ... )
      or $object->${\$action->{doit}}(...)
Re: How do I create a reference to an object method?
by pc88mxer (Vicar) on Jun 25, 2008 at 19:13 UTC
    You could use a string:
    my $action = { dosomething => 'something' }; my $method = $action->{dosomething}; $obj->$method(@args);
    You could also use a closure:
    my $action = { dosomething => sub { shift->something(@_) } }; my $whattodo = $action{dosomething}; $whattodo->($obj, @args);
      I was thinking about that, but I forgot about the arrow for use with hashes! It works, thank you.