开发者

Call a perl module's method from a string

开发者 https://www.devze.com 2023-03-11 04:50 出处:网络
Given a perl module Foo.pm with methods aSub() and bSub() my $obj = Foo->new(); my $x = $obj->aSub($argA);

Given a perl module Foo.pm with methods aSub() and bSub()

my $obj = Foo->new();
my $x = $obj->aSub($argA);
my $y = $obj->bSub($argB);

I have a TAP program where I build an array of hashes:

my $test_case = [
   'aSub' => "foobar",
   'bSub' => "whobar"
];  

I would like to be able to parse the array and use the key/value elements to call methods on the Foo object $obj;

Like a static method:

if ($key eq 'aSub') {
  $obj->aSub($value)
} elsif ($key eq 'bSub') {
  $obj->bSub($value);
}
...

I would prefer to do this polymorphically so I don't have to hard code the methods:

$obj->{$key}($value) #or something of the sort  

I have tried several methods using references and/or glob, but I keep on getting an error:

Error: Threw an exception: aSub is not defined

Test::Harness capturi开发者_开发知识库ng the error and printing less useful message?


Calling a method whose name is in a variable is easy:

my $key = 'aSub';
my $value = 'foobar';
my $obj = Foo->new();

$obj->$key($value);
0

精彩评论

暂无评论...
验证码 换一张
取 消