crenz has asked for the wisdom of the Perl Monks concerning the following question:

Fellow monks,

for some module, I need to include other modules based on run-time information. Here's roughly what I am doing right now:

sub init { my ($someModule, $someCondition) = @_; eval "use Acme::$someModule"; eval "use Funky::Library" if $someCondition; } init("Bleach", 1);

Now, for some reason, I don't really like eval "$some $code". I fear the performance hit (although I have no idea whether there really is one), and more importantly I just don't like the thought of compiling during runtime. I guess I could rewrite the code using require and import, like this:

sub init { my ($someModule, $someCondition) = @_; require "Acme/$someModule.pm"; import "Acme/$someModule.pm"; if $someCondition { require Funky::Library; import Funky::Library qw(grooves moves); } } init("Bleach", 1);

Is this the canonical way to solve that problem; are there any issues I need to be aware of?

Replies are listed 'Best First'.
Re: run-time module usage
by Courage (Parson) on Aug 02, 2002 at 19:54 UTC
    Your guess is exactly right: namely, it really is a canonical way to solve your mentioned problem. You could add some error-checking using
    eval { # your mentioned "require" and "import" statements go here } if ($@) { # something smells fishy here, or my name is Stinky Lulu }
    which is a special case of try-block.

    Courage, the Cowardly Dog.

Re: run-time module usage
by Zaxo (Archbishop) on Aug 02, 2002 at 21:25 UTC

    It's too new for this to be a general recommendation, but with perl-5.8.0 you can say:

    use if $someCondition, 'Funky::Library';

    Yes, there is a pragmatic if.pm behind that.

    After Compline,
    Zaxo

Re: run-time module usage
by crenz (Priest) on Aug 02, 2002 at 21:11 UTC

    Update and Bonus Question: Consider

    # 1 my $m = "Module.pm"; require $m; import $m qw(something); # 2 require "Module.pm"; import "Module.pm" qw(something);

    Number one works fine. Number two doesn't. Why? perl complains

    String found where operator expected (...) (Do you need to predeclare import?)

    and under Windows, I even get a Out of Memory