Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Loading a module at runtime

by jhisey (Initiate)
on May 04, 2011 at 22:40 UTC ( #903013=perlquestion: print w/replies, xml ) Server Error (Error ID 8064518c45859)

An error has occurred. The site administrators have been notified of the problem and will likely soon fix it. We thank you, for you're patients.

Need Help??
jhisey has asked for the wisdom of the Perl Monks concerning the following question:

I swear I've done this before but can't get it to work now. I'm trying to load a module at runtime based on a variable. Previously, I'm positive I did it using eval but for some reason it's not working for me. For example:
if ($DEBUG) { eval { use SOAP::Lite +trace => 'debug'; }; } else { eval { use SOAP::Lite; }; }
One thing that is different now then last time I did this is this is inside of a .pm itself. Would that have any bearing on when the SOAP::Lite module gets loaded? It always loads with +trace on in this scenario. Thanks!

Replies are listed 'Best First'.
Re: Loading a module at runtime
by runrig (Abbot) on May 04, 2011 at 22:53 UTC
    Read the docs for eval. With eval { BLOCK } the code in BLOCK is parsed at 'compile' time. With eval $string the code in $string can not be parsed until 'runtime'. use is executed before runtime. Perhaps your evals worked when the contents were strings. Perhaps you want to use require (update: I see you have an import list...That would require SOAP::Lite->import(@list). And you probably want to wrap this logic in a BEGIN {} block.
      Just an FYI, this is how I finally got it working:
      if ($DEBUG) { eval "use SOAP::Lite; SOAP::Lite->import(+trace => 'debug');"; } else { eval "use SOAP::Lite;"; }
        use SOAP::Lite; use if $DEBUG, qw[ SOAP::Lite +trace debug ];
Re: Loading a module at runtime
by wind (Priest) on May 05, 2011 at 00:36 UTC

    As documented in use, require and accessing import directly should get what you want.

    The BEGIN block is optional depending on where you want this done:

    BEGIN { require SOAP::Lite; SOAP::Lite->import($DEBUG ? qw(+trace debug) : ()); }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://903013]
Approved by toolic
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2016-08-29 20:42 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (409 votes). Check out past polls.