• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 450
  • Last Modified:

Perl - Dynamic Packages

I'm dynamically reading in a variety of packages and need to be able to pass the appropriate package name as a variable under strict (not strict 'refs'). Then I need to test whether a dynamically named subroutine exists in that namespace and then execute it if it does.

In essence:
1. pass package name as a variable to a function in the main:: namespace
2. pass subroutine name to the same function
3. check whether that subroutine has been defined in the package
4. if it has, execute the subroutine

for example (this does not work)
sub test {
 my $packageName = shift;
 my $functionName = shift;

 if (${{$packageName}::{$functionName}}){ # throws bareword error
    &{{$packageName}::{$functionName}}; # which of course just doesn't work
}

I have found this lookup of the symbol table to work:
if (${PackageName::{$functionName}})
but of course in that example, PackageName:: is the hard-coded package name and not dynamic at all.

I've also seen ozo and other suggest a construct like
if (${"$packageName"}->{$functionName})

but I haven't been able to get that to work either.

Any advice is appreciated! I'm trying to refactor some code but don't have the scope to rewrite this as proper classes, so namespaces is all I've got to work with here.

Thanks

Tom

I have messed around with about every permu
0
tomaugerdotcom
Asked:
tomaugerdotcom
  • 6
  • 3
  • 2
2 Solutions
 
wilcoxonCommented:
This will work even with strict refs...
use strict;
test($pkg, $sub);

sub test {
    my ($pkg, $sub) = @_;
    eval "use $pkg";
    if ($@) {
        print "package $pkg does not exist\n";
        return;
    }
    eval "&${pkg}::$sub()";
    if (not $@) {
        print "sub ${pkg}::$sub executed successfully\n";
    }
}

Open in new window

0
 
Adam314Commented:
To determine if a package can execute a sub:

my $pkg = 'PackageName';
my $sub = 'SubName';
if($pkg->can($sub)) {
    #Package can run sub
}
else {
    #Package can not run sub
}
0
 
tomaugerdotcomAuthor Commented:
@ wilcox - thanks for this: an adaptation of your code works. I'd like to find a non-eval solution if possible.

@ Adam314 "can" is not documented under perlfunc - where did you come up with that one, and will it run under all versions of Perl or just ActiveState?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Adam314Commented:
I use it on a version of perl I compiled from source code on Ubuntu Linux (Debian type distro), and it works just fine.

Do not remember where I learned about it.  I do see it is not well documented, if documented at all.  Not sure which version of perl it first became available either.
RunIfPossible('TestGroup::TestPackage', 'SomeSub');

sub RunIfPossible {
	my ($package, $sub) = @_;
	my $package_fn = $package;
	$package_fn =~ s/::/\//g;
	require "$package_fn.pm";
	if($package->can($sub)) {
		print "Package '$package' can do '$sub'\n";
		$package->$sub();
	}
	else {
		print "Package '$package' can not do '$sub'\n";
	}
}

Open in new window

0
 
wilcoxonCommented:
If you want to avoid eval, Adam314's suggestion is probably the best.  I'd heard about can but forgot about it as I've rarely used it.

can definitely works on Unix versions of perl - as Adam314 said, I'm not sure which version added it (pretty sure it was in at least as far back as 5.6.0).
0
 
tomaugerdotcomAuthor Commented:
Right on guys. Thanks for the great help.

Keep up the great work!

T
0
 
tomaugerdotcomAuthor Commented:
Thanks for the detailed and accurate responses.
0
 
tomaugerdotcomAuthor Commented:
Wilcoxon, I was going to ask what the construct ${packageName} was all about. To me that just doesn't make sense because now packageName is a bareword. Why is it ${packageName} and not {$packageName}?

Thanks for taking the extra time.
0
 
wilcoxonCommented:
It's mostly just habit.  I think it's a special case (it works fine under use strict and use warnings).  In shell programming, $packageName::xxx will cause an error (in perl $packageName::xxx and ${packageName}::xxx just result in very different outcomes) - making it ${packageName}::xxx causes it to end the variable before the colon.  ${packageName} and {$packageName} are probably equivalent in perl in "open" scope but will result in very different results in some cases (such as inside a string).

The ${var} construct also has two other common uses for me (besides putting :: after a var):
* allow things like "${var}_xxx" (eg use $var inside a string with other var-legal chars adjacent)
* (very rarely) allow "illegal" variable names (a glance through perlvar will show ${^VAR} is legal)
0
 
tomaugerdotcomAuthor Commented:
Thanks, wilcoxon, that's extremely helpful.
0
 
tomaugerdotcomAuthor Commented:
Just a quick update for anyone else experiencing similar challenges:

the problem with eval "${packageName}::$functionName" as a means for testing to see whether the function exists within the package is that it actually executes the function. Now this may be a trivial distinction depending on what you want your code to do, but if you need a test only you should use the if ($packageName->can($functionName)) construction instead.

I don't really understand how $packageName is magically turned into a hashref, but hey it's Perl, and full of little mysteries like that.

Incidentally, functionally eval "${packageName}::$functionName" is identical to eval "&{${packageName}::$functionName}", which also makes little to no sense to me. But I suppose we're playing on the very boundaries of the language and so weirdness is to be expected.
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 6
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now