13.7. Calling Methods IndirectlyProblemYou want to call a method by a name that isn't known until run time. SolutionStore the method name as a string in a scalar variable and use it where you would use the real method name to the right of the arrow operator:
$methname = "flicker";
$obj->$methname(10); # calls $ob->flicker(10);
# call three methods on the object, by name
foreach $m ( qw(start run stop) ) {
$obj->
Discussion
Sometimes you need to call a method whose name you've stored somewhere. You can't take the address of a method, but you can store its name. If you have a scalar variable @methods = qw(name rank serno); %his_info = map { $_ => $ob->$_() } @methods; # same as this: %his_info = ( 'name' => $ob->
If you're desperate to devise a way to get a method's address, you should try to rethink your algorithm. For example, instead of incorrectly taking my $fnref = sub { $ob->method(@_) }; Now when it's time to call that indirectly, you would use: $fnref->(10, "fred"); and have it correctly really call: $obj->method(10, "fred");
This works even if
The code reference returned by the UNIVERSAL For example, this is highly dubious code: $obj->can('method_name')->($obj_target, @arguments) if $obj_target->isa( ref $obj );
The problem is that the code ref returned by See Alsoperlobj (1); Recipe 11.8 Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|