Conditionally loading a module is very easy. The only thing to avoid is a bare use statement, because use is executed at compile time. For example:
if ($use_socket) { use Socket; # oops! Socket will get loaded at compile-time # before $use_socket is even evaluated }
So, you can either eval a use statement, or require the module and then call import. (I prefer the second approach.)
if ($use_socket) { eval "use Socket"; # ok: Socket gets loaded at run-time # if $use_socket is true }
if ($use_socket) { require Socket; # ok: Socket gets loaded at run-time Socket->import(); # if $use_socket is true }

 

However, you may need more than that, because you're planning to load the modules from a controller module. If the modules you're loading export anything, you probably want to export them into the package that called the controller module. That is, maybe you'll have the controller module load Socket, but then you want to call the Socket functions from the main script.

The Exporter module, which provides a basic import() method, also provides export_to_level(). export_to_level() does an import to a package farther up in the call tree. For modules which inherit from Exporter, such as the Socket module, you can call the export_to_level() method to get the behavior you need:

if ($use_socket) { require Socket; Socket->export_to_level(1, @_); }
Unfortunately, not every module inherits from Exporter or defines its own export_to_level() method. CGI, for example, doesn't have an export_to_level() method. I'm afraid I don't know a good approach for a situation like this. But I hope this was enough to get to you started!

In reply to Re: Best/possible ways to dynamically use modules by chipmunk
in thread Best/possible ways to dynamically use modules by pdt1630

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.