?
Solved

Perl - Dynamic Packages

Posted on 2010-01-12
11
Medium Priority
?
438 Views
Last Modified: 2012-05-08
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
Comment
Question by:tomaugerdotcom
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 2
11 Comments
 
LVL 26

Accepted Solution

by:
wilcoxon earned 1400 total points
ID: 26300610
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
 
LVL 39

Assisted Solution

by:Adam314
Adam314 earned 600 total points
ID: 26305581
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
 
LVL 14

Author Comment

by:tomaugerdotcom
ID: 26306397
@ 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
Technology Partners: 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!

 
LVL 39

Expert Comment

by:Adam314
ID: 26307130
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
 
LVL 26

Expert Comment

by:wilcoxon
ID: 26310923
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
 
LVL 14

Author Comment

by:tomaugerdotcom
ID: 26313845
Right on guys. Thanks for the great help.

Keep up the great work!

T
0
 
LVL 14

Author Closing Comment

by:tomaugerdotcom
ID: 31676456
Thanks for the detailed and accurate responses.
0
 
LVL 14

Author Comment

by:tomaugerdotcom
ID: 26313876
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
 
LVL 26

Expert Comment

by:wilcoxon
ID: 26314621
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
 
LVL 14

Author Comment

by:tomaugerdotcom
ID: 26315888
Thanks, wilcoxon, that's extremely helpful.
0
 
LVL 14

Author Comment

by:tomaugerdotcom
ID: 26362248
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question