|more useful options|
Dynamic Method Callsby ton (Friar)
|on Aug 28, 2001 at 01:17 UTC||Need Help??|
ton has asked for the
wisdom of the Perl Monks concerning the following question:
Some background first (skip next two paragraphs if you don't care):
I have a class (Foo) that reads in an XML-style configuration file and makes the information available to the caller via a bunch of AUTOLOADed methods. This worked fine for a while, but then the amount of data within Foo got larger, and the number of people maintaining Foo also increased, and it became unmanagable to keep all the parsing and accessing within the same class. I therefore rewrote Foo as a container, with various block objects to parse and store the different sections of the config. In other words, Foo is now little more than an array of block objects with an enumerator, and the block objects do the real work. So far, so good.
I now need to take the AUTOLOADed methods that Foo catches and call them on the current block object. So if a caller does something like $myFoo->Bar(), I need to call the Bar method of the current block. I should mention that the blocks exist within a class hierarchy, so the methods that the class implements might not be in the class package. Ick.
The Problem: I need to call dynamically determined methods on an object, where the method name is contained in a string. As an additional complication, the method might not be in the class receiving the call; it can be in one of its superclasses. An example might help:
Say I have the following class in MyClass.pm:
and I have code calling the class like this:
This works fine. Now suppose that I have a subclass of MyClass named MySubClass (in MySubClass.pm), which looks like this:
and I change the test code to use MySubClass instead of MyClass:
This will fail with the message "Undefined subroutine &MySubClass::HelloWorld called at test.pl line 9". It appears that perl is looking for HelloWorld within MySubClass.pm, and won't look in packages specified in the @ISA array. Incedentally, calls like "$pack->HelloWorld()" work fine.
So my question is the following: Is there some way I can get method behavior (looking though the namespaces in the @ISA package) when I don't know the name of the method until runtime? Or do I have to look through the @ISA array myself?
Any help would be appreciated,