in reply to How to access an object method when method name is stored in scalar variable

my $return_value = $obj->$method;
  • Comment on Re: How to access an object method when method name is stored in scalar variable
  • Download Code

Replies are listed 'Best First'.
Re^2: How to access an object method when method name is stored in scalar variable
by tj_thompson (Monk) on Mar 15, 2011 at 21:22 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"};

        And this approach is fully orthogonal for passing parameters:

        >perl -wMstrict -le " { package Foo; sub new { return bless { foo => 'woo' } => shift; } sub hoo_foo { my $self = shift; print qq{hi from hoo_foo: $self->{$_[0]}}; } } ;; my $oo = Foo->new; my $poo = 'foo'; my $method = qq{hoo_$poo}; $oo->$method($poo); $oo->${ \qq{hoo_$poo} }($poo); " hi from hoo_foo: woo hi from hoo_foo: woo
        Haha so the straightforward obvious easy way to do it huh? *sigh* I hate missing those. Thank you once again :)