Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Loading a module at runtime

by jhisey (Initiate)
on May 04, 2011 at 22:40 UTC ( #903013=perlquestion: print w/ replies, xml ) 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!

Comment on Loading a module at runtime
Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (10)
As of 2014-07-31 15:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (249 votes), past polls