Re: Use with variable
by borisz (Canon) on Sep 08, 2004 at 13:11 UTC
|
Yes, maybe you need to call import yourself.
$mod = "Digest::MD5";
eval "require $mod";
| [reply] [d/l] |
|
my $mod = "Digest::MD5";
eval "use $mod";
and avoid calling import yourself...
And don't forget to check $@...
| [reply] [d/l] |
|
my $module = "Digest::MD5";
eval 'use $module'; # note single quotes
That's because use $var actually works. You just have to somehow populate $var before the compile-time effect of use takes place. A BEGIN block lets you do that. Silly example:
my $module;
BEGIN { $module = "Digest::MD5"; }
use $module;
Note that the snippets of course aren't equivalent — the first loads the module at runtime, the second loads it at compile time.
Makeshifts last the longest.
| [reply] [d/l] [select] |
Re: Use with variable
by Corion (Patriarch) on Sep 08, 2004 at 13:08 UTC
|
BEGIN { require Module; import Module LIST; }
except that Module *must* be a bareword.
So, you can easily do it like the following:
my $module = "CGI";
$module->require;
$module->import;
Update: Fixed the ugly bug I introduced. Thanks to tomhukins for spotting it.
Update 2: I should test before I promise broken things as fixed. See my reply to edan further down | [reply] [d/l] [select] |
|
| [reply] [d/l] |
|
| [reply] [d/l] |
|
my $module = "CGI";
my $filename = $module;
$filename =~ s!::!/!g;
$filename .= ".pm";
require $filename
or die "$module did not return a true value";
$module->import;
(this time tested it ...) | [reply] [d/l] |
|
|
|
Re: Use with variable
by radiantmatrix (Parson) on Sep 08, 2004 at 14:36 UTC
|
Others have answered (the eval route is the way I'd go); but I have a question. Was your query merely curiosity, or have you actually found a use for this technique?
I've never encountered a problem where this was the solution, and I'm just curious from a "hey, that's really unusual" point-of-view. Would you mind sharing more about what you're doing?
--
$me = rand($hacker{perl});
| [reply] |
|
It's easy to think of applications for this technique. Any sort of "plug-in" or "load-on-request" situation. Or "drivers", for instance. Ever use DBI? Notice how you only have to "use DBI;" and then the appropriate "DBD::*" module is loaded according to the datasource in your DBI->connect() call? That magic is done by dynamically loading a module that is contained in, yes, you guessed it, a variable! Actually, the eval method is used there:
# --- load the code
my $driver_class = "DBD::$driver";
eval qq{package # hide from PAUSE
DBI::_firesafe; # just in case
require $driver_class; # load the driver
};
if ($@) {
#....
| [reply] [d/l] |
|
| [reply] |