in reply to How can I call a Perl sub with an object from a sub name stored in a var?
Perhaps it would help if you showed the implementation code, instead of just a single line, because it works fine for me:
package Foo; use warnings; use strict; sub new { return bless {}, $_[0]; } sub blah { my ($self, $args) = @_; my $method = 'process'; my $updated = $self->$method($args); return $updated; } sub process { my ($self, $args) = @_; my @updated; push @updated, $_ * 2 for @$args; return \@updated; } package main; my $obj = Foo->new; my $method = 'blah'; my $args = [qw(1 2 3)]; my $return = $obj->$method($args); print "$_\n" for @$return;
Output
spek@scelia ~/scratch $ perl obj.pl 2 4 6
In my test suites, I very often put package and method names within variables to shorten the amount I have to type, as in each test file, I have a block for each group of tests, and there can be hundreds of tests, so instead of dozens of:
# test A { my $object = Some::Package::Name->new; is $object->some_method_name($y), 1, "some_method_name() with arg +$y ok"; ... } # test B { my $object = Some::Package::Name->new; is $object->some_method_name($z), 2, "some_method_name() with arg +$z ok"; ... } ...
I do this:
... my $mod = 'Some::Package::Name'; my $m = 'method_tested_in_this_test_file'; # testA { my $o = $mod->new; is $o->$m($arg), 1, "return val of $m with arg $arg ok"; ... } # testB { my $o = $mod->new; is eval {$o->$m('blah'); 1}, undef, "$m croaks if sent in 'blah'"; like $@, qr/idiot!/, "...and error message is sane"; ... } ...
And so on and so forth.
Update: Modified example to show method name as string within the object ($self) as well as outside of it.
|
|---|