I have a script that will parse a list of packages. The actual list of packages is not known till run time. Some of these packages have a couple subroutine. The name of the subroutine is fixed (preBuild and postBuild). I am having trouble invoking these sub-routines. Below code illustrates my attempts. Question is: How to call a function which may exist, while ignoring it when it doesn't.
foreach my $p (@pkgList) {
$funcName="$p::preBuild";
## 1. doesn't work. Never defined
if (defined (&$funcName)) {
&$funcName
}
## 2. Cops out first time it hits a packet without the subroutine
if (ref (&$funcName) eq "CODE") {
&$funcName
}
## 3. same as 2.
eval $funcName
}
Perl provides the UNIVERSAL base class for all packages, and UNIVERSAL provides the can(subname) method. With this you can test for the availability of arbitrary functions in arbitrary packages.
sub Foo::foo { 42 }
sub Baz::foo { 19 }
foreach $pkg (qw(Foo Bar Baz Quux)) {
if ($pkg->can('foo')) {
print "foo in $pkg: ", $pkg->foo(), "\n";
} else {
print "foo in $pkg: not found\n";
}
}
Output:
foo in Foo: 42
foo in Bar: not found
foo in Baz: 19
foo in Quux: not found
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