genesi5
genesi5

Reputation: 453

Perl, cannot require a module dynamicaly from @INC

So, i've got a problem with loading a module via require. We have a working directory. The program loads a PACKAGE (bolded not to make you confused) (which is ok - thanks to correct and local namespaces), but it has to load another module from very different directory. So, as i've heard, it should be unshifted into @INC in BEGIN block. But....This begin should take a param (currently from initial programm), containing some path to configuration file, which containing parameter i need (path to module, which i need to unshift).

BEGIN inited, i check @INC - unshift seems to be succeed. Then, in PACKAGE methods we need to load this module, but when i try to do something like:

eval{
    print STDERR "Trying...\n";
    my $path = "path/to/module"; # contains "DIR" dir and "Module.pm", 
    # also tried to write this path as "path/to/module/DIR/Module.pm"
    require $path;
    DIR::Module->import();
    print STDERR "Success\n";
    1;
} or {print STDERR "Failed\n";}

my $module = DIR::Module->new();

And I got "Trying.." and "Failed". Tried use lib with fullpath - got nothing. What am i doing wrong?

Upvotes: 0

Views: 80

Answers (1)

ikegami
ikegami

Reputation: 385546

You say $path is the path to the module, but you also say it's the path to the directory containing DIR/Module.pm. I'm assuming it's the latter because it needs to be the former.

my $path = "/path/to/lib";
require "$path/DIR/Module.pm";

Remember to use $RealBin if the path is relative to your script.

use FindBin qw( $RealBin );

my $path = "$RealBin/../lib";
require "$path/DIR/Module.pm";

Note that it rarely makes sense to import from a dynamically loaded module.


If there's no reason to avoid loading this module at compile-time, I'd go with

use lib qw( /path/to/lib );
use DIR::Module;

Again, remember to use $RealBin if the path is relative to your script.

use FindBin qw( $RealBin );
use lib "$RealBin/../lib";
use DIR::Module;

Upvotes: 5

Related Questions