8

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 capturing the error and printing less useful message?

2
  • 1
    $test_case as you defined it is not an array of hashes, it's just an array of strings (it's the same as $test_case = [qw(aSub foobar bSub whobar)]). Commented Jun 8, 2011 at 23:45
  • very good. My actual array looks like [<scalar>, <hash>, <scalar>..]. My everything was looking like a scalar to my test, so it was never reaching the proper point. The exception/error must be getting thrown by the module Foo that is trying to interpret 'aSub' as a valid argument to $obj->bSub($target); Commented Jun 9, 2011 at 0:22

1 Answer 1

15

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

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

$obj->$key($value);
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct, though the source of the error was really in my data structure. Since you pointed that out as well, I think you deserve the win.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.