I think I understand why this doesn't work but I'm having trouble coming up with a way around it.
I'm working on a bot that can talk on a variety of protocols. I want to be able to load the appropriate protocol when the bot starts and keep the code for each protocol in its own separate package. To do this I used the following code:
sub init { my $pkg = shift; my $proto = shift || $config->protocol(); no strict 'refs'; eval "require Bot::Protocol::$proto"; if($@) { croak "Failed to load $proto.\n"; } }
So far, so good. This works as long as my Bot::Protocol::$proto simply executes. However, I'd like to pass parameters to my protocols so that I don't have to include the config again etc. I tried using Exporter within the file I was requiring and then calling the sub. I tried a test case to eliminate the irrelavent parts
# in the main my $pkg = shift; no strict 'refs'; eval "require $pkg"; if($@) { croak "Failed to load $pkg: $@\n"; } print foobar();
And with the test I wrote two small packages, 'Foo' and 'Bar':
# in Foo.pm package Foo; use strict; use Exporter; use vars qw(@ISA @EXPORT); @ISA = qw(Exporter); @EXPORT = qw(foobar); sub foobar { return "Foo!"; } 1;
(Bar.pm looks the same except it returns "Bar")
However of course I get "Undefined subroutine &main::foobar(). Now if I call it directly after I've required it with the eval, i.e. Foo::foobar() it works but to do that in my project I would have to use eval again as in eval "$pkg::foobar()", which seems a bit redundant. There must be a way to export it to everyone. Thanks in advance!
Lobster Aliens Are attacking the world!In reply to Exporting subs from package required in an eval by cfreak
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |