Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

use or require ?

by faro (Novice)
on Oct 01, 2007 at 08:43 UTC ( #641852=perlquestion: print w/replies, xml ) Need Help??

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

Greetings monks. I have this piece of code:
use My::AAA; use My::BBB; use My::CCC; my $module = 'My::' . $name_str; eval { $obj = $module->new(); }; if ($@) { print "Error loading module $module: $@\n"; exit; } $obj->login();
I would like to put the modules loading dinamically:
eval { use "$module" };
eval { require "$module" };
Somehow i'm not getting this to work, any tips ? Thanks in advance

Replies are listed 'Best First'.
Re: use or require ?
by Corion (Patriarch) on Oct 01, 2007 at 08:51 UTC

    Basically, you want:

    (my $filename = $module) =~ s-::|'-/-g; $filename .= ".pm"; require $filename or die "Couldn't load '$filename': $!";

    If you want this to be more equivalent to use, wrap it in a BEGIN block.

Re: use or require ?
by jeanluca (Deacon) on Oct 01, 2007 at 09:01 UTC
Re: use or require ?
by valdez (Monsignor) on Oct 01, 2007 at 12:37 UTC


    in similar cases I use UNIVERSAL::require; from module 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 $@ }

    Ciao, Valerio

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://641852]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2022-06-25 19:05 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (83 votes). Check out past polls.