Perl already provides a built-in function to do this. It is the 'can' function which in contained in the UNIVERSAL package which every module inherits from.
From the Advanced Perl Programming Book(O'Rielly):
Chapter 7.3 UNIVERSAL
All modules implicitly inherit from a built-in module
called UNIVERSAL and inherit the following three methods:
isa (package name)
For example, Rectangle->isa('Shape') returns true if
the Rectangle module inherits (however indirectly) from
the Shape module.
can (function name)
Rectangle->can('draw') returns true if the Rectangle
or any of its base packages contain a function called draw.
VERSION (need version)
If you say,
package Bank;
$VERSION = 5.1;
and the user of this module says,
use Bank 5.2;
Perl automatically calls Bank->VERSION(5.2), which
can, for instance, make sure that all libraries required
for version 5.2 are loaded. The default VERSION method
provided by UNIVERSAL simply dies if the Bank's $VERSION
variable has a lower value than that needed by the user of
the module.
Because Perl allows a package to shamelessly trample on
other namespaces, some packages use the UNIVERSAL module
as a holding area for some global subroutines that they
wish to export to everyone. I recommend that you do not
use this "feature" yourself (or at least not in those that
you contribute to CPAN!).
| [reply] |
sub method { }
package Pkg;
sub method_pkg { }
package main;
print defined '&method', "\n",
main->can('method'), "\n",
Pkg->can('method'), "\n",
Pkg->can('method_pkg'), "\n";
#
| [reply] |