i have script parse list of packages. actual list of packages not known till run time. some of these packages have couple subroutine. name of subroutine fixed (prebuild , postbuild). having trouble invoking these sub-routines. below code illustrates attempts. question is: how call function may exist, while ignoring when doesn't.
foreach $p (@pkglist) { $funcname="$p::prebuild"; ## 1. doesn't work. never defined if (defined (&$funcname)) { &$funcname } ## 2. cops out first time hits packet without subroutine if (ref (&$funcname) eq "code") { &$funcname } ## 3. same 2. eval $funcname }
perl provides universal
base class packages, , universal
provides can(subname)
method. can test 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
Comments
Post a Comment