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!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.