Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a function which may exist within a package

Tags:

package

perl

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
}
like image 206
Ravi Kumar Avatar asked Jan 30 '26 02:01

Ravi Kumar


1 Answers

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
like image 128
mob Avatar answered Feb 01 '26 20:02

mob