Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Need help in dynamically loading a module

by Sri Harsha (Initiate)
on Feb 15, 2012 at 07:58 UTC ( [id://953860]=perlquestion: print w/replies, xml ) Need Help??

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

Consider I have two modules mod1.pm & mod2.pm. Based on a condition i would like use a module say,

#main script if($module) { use mod1; } else { use mod2; } test(); #mod1.pm sub test { print "Test"; } #mod2.pm sub test { print "Test1"; }

Issue:

Even when the $module is true, it still invokes the "sub test" in mod2.pm:( Am I doing something wrong or this approach is not possible?

Replies are listed 'Best First'.
Re: Need help in dynamically loading a module
by Corion (Patriarch) on Feb 15, 2012 at 08:15 UTC

    Have you looked at use? It shows what use Module; really is, and how you can make it conditional.

Re: Need help in dynamically loading a module
by AnomalousMonk (Archbishop) on Feb 15, 2012 at 08:49 UTC

    Also, perhaps take a look at the if module.

Re: Need help in dynamically loading a module
by philipbailey (Curate) on Feb 15, 2012 at 08:44 UTC

    use statements are run at compile time, in an implicit BEGIN block. They are run wherever they appear in your code, irrespective of whether they appear (as in your case) in conditional statements.

    Instead, use require, which is evaluated only at run time. Wrap it in an eval and test $@ to check whether the require succeeded.

Re: Need help in dynamically loading a module
by sundialsvc4 (Abbot) on Feb 15, 2012 at 15:02 UTC

    There’s More Than One Way To Do It.™

    • The hard way:   eval "require $f00;"   (... bah...)
    • The easy way:   UNIVERSAL::require.

    I use this technique successfully in a hairy old FastCGI program which employs Perl modules for its (hundreds of...) individual screen handlers.   At one time, this site was very popular with hardware vendors who touted just how much RAM a particular unit could hold.   Now, web page handlers are loaded on-demand, and the processes intentionally die-off after processing a few ten-thousand requests so that the modules don’t accumulate over the course of days or weeks of uptime.   The key modules used all the time and by everyone are brought in at startup time by use.   Once a module has been loaded once, it stays, and (AFAIK...!) nothing further happens if any of them are requested again.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-19 06:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found