I want to use a method of an object. Like $myObject->helloWorld()
.
However there are a couple of methods so I loop through an array of method names and call the method like this:
my $methodName ="helloWorld"; $myObject->$methodNames;
This works quite nice but some objects don't have all methods.
How can I tell whether $myObject
has a method called helloWorld
or not?
You can use the UNIVERSAL::can
method of all objects to determine what methods it supports:
if ($myObject->can($methodName)) { $myObject->$methodName; }
As Eric noted, you can usually use UNIVERSAL::can
It can be used either on an object as in your example ($obj->can($methodName)
) or statically, on a class: (CLASS->can($methodName)
)
Please note that there are possible false negatives associated with using UNIVERSAL::can
on objects/classes which have AUTOLOAD-ed methods - see the perldoc for details. So before using can()
on an object/class, please be careful to verify that the class in question either does not use AUTOLOAD, or overrides can()
to compensate, or uses forward declaration to compensate as described in can()
's perldoc - hat tip to brian d foy)
Also, please be careful to either ONLY call can()
on actual objects, or encapsulate it in eval. It will die if called on a non-object (e.g. undef, scalar etc...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With