Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Need help in dynamically loading a module

by Sri Harsha (Initiate)
on Feb 15, 2012 at 07:58 UTC ( #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 & Based on a condition i would like use a module say,

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


Even when the $module is true, it still invokes the "sub test" in 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 (Pope) 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 philipbailey (Chaplain) 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 AnomalousMonk (Canon) 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 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://953860]
Approved by philipbailey
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2017-02-20 12:31 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (295 votes). Check out past polls.