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

Assuming I have an obj reference $obj, that has a method foo such that $obj->foo returns something, what's the easiest way to get the return value of $obj->foo if the method name is stored in a scalar $method?

You can do:

# want the result of $obj->foo stored in $return_value my $method = 'foo'; my $return_value; eval '$return_value = $obj->'.$method; # now $return_value has what you need

But this seems clumsy and I doubt it's the best way. What's the right way to do this?

  • Comment on How to access an object method when method name is stored in scalar variable
  • Download Code

Replies are listed 'Best First'.
Re: How to access an object method when method name is stored in scalar variable
by Eliya (Vicar) on Mar 15, 2011 at 21:18 UTC
      You know, I didn't even try that. I had already decided it definitely wouldn't work. Thank you sir :)

      So, how about the case where you have a partial method name in the scalar instead such as wanting to access $obj->set_foo but $method only has 'foo' in it? I'm guessing you're stuck with the eval method this time?

        You can always create a new scalar that holds the full method name before making the call :)

        my $method = "foo"; my $full_method = "set_$method"; my $return_value = $obj->$full_method;

        Or you could even do  (though that's a bit ugly):

        my $ret_value = $obj->${\"set_$method"};
Re: How to access an object method when method name is stored in scalar variable
by locked_user sundialsvc4 (Abbot) on Mar 16, 2011 at 15:35 UTC

    Actually, there’s a compelling reason why you might want to specify the methods that are to be called through the use of strings (in the manner suggested in the replies), rather than by explicit method-pointers.   If you call a method by specifying the name of the method that you wish to call, Perl will perform the name-resolution for a given object “on the fly” at that time, thus properly locating any methods that you may have overridden.   Whereas, if Perl sees that the variable contains a sub reference, then that sub will be the one that is called, whether it is the one that you intended to call or not.

    (If what I just said, sounded vague or tentative, then there is a reason.   “Behold, these are Arkane Mysteries, known to The Wise Elders, and I am but a simple monk ...”)