Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

use or require ?

by faro (Novice)
on Oct 01, 2007 at 08:43 UTC ( [id://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" };
or
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

    Ciao,

    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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-19 09:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found