Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

"use" dynamic module

by rsennat (Beadle)
on Dec 06, 2005 at 06:16 UTC ( #514339=perlquestion: print w/replies, xml ) Need Help??

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

hi all,

how do i "use" a module name in a scalar variable??
$mod = "my_module"; use $mod;
How to achieve this kind of usage?? Actually this throws an error.
thanks

Replies are listed 'Best First'.
Re: "use" dynamic module
by ikegami (Pope) on Dec 06, 2005 at 06:24 UTC
    my $file = $mod; $file =~ s{::}{/}g; $file .= '.pm'; eval { require $file; }; die("Unable to load $mod: $@\n") if $@;

    should do what you want.

    Note that it executes at run-time (while use executes at compile-time), but that's probably fine. Wrap the code in a BEGIN { } block if you need to execute this at compile-time.

    Note that it doesn't import symbols, but that's probably a good thing for dynamically loaded modules. Add $mod->import if $mod->can('import'); if you need to import symbols.

    Update: PodMaster suggested that I provide these links: use, require.

      For a prepackaged approach, it might be worth considering UNIVERSAL::require. Its synopsis:

      # This only needs to be said once in your program. require UNIVERSAL::require; # Same as "require Some::Module" my $module = 'Some::Module'; $module->require or die $@; # Same as "use Some::Module" BEGIN { $module->use or die $@ }

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      $mod->import if $mod->can('import');
      No can() check needed; if there's no import, $mod->import() is silently a noop (even if there is an AUTOLOAD!).

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (11)
As of 2020-02-26 20:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?










    Results (117 votes). Check out past polls.

    Notices?