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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.