Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an object has a specific method?

Tags:

perl

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?

like image 558
jantimon Avatar asked Apr 15 '10 16:04

jantimon


2 Answers

You can use the UNIVERSAL::can method of all objects to determine what methods it supports:

if ($myObject->can($methodName)) {     $myObject->$methodName; } 
like image 148
Eric Strom Avatar answered Oct 13 '22 02:10

Eric Strom


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...)

like image 34
DVK Avatar answered Oct 13 '22 01:10

DVK