Lazer
Lazer

Reputation: 94790

How can I tell perl the path for a module?

I use a perl module file in my perl script:

printtab.pl

use Table;

Table.pm is present in the same directory as printtab.pl, so as long as I am executing printtab from the directory, it executes fine.

But If I execute it from some other place, for example, using a cronjob, I get an error mentioning that the module is not found in @INC.

What is the correct way to resolve this?

I tried

push @INC, "/path/Table.pm";

but it does not work. Can you tell me why?

I found about use lib and it works correctly

use lib "/path";

Is use lib the best method in such a situation?

Upvotes: 4

Views: 607

Answers (3)

pavel
pavel

Reputation: 3498

use lib is a good option. But is you place your modules in the same directory as your programs (or in a sub-directory relative to the one containing your programs), you could use use FindBin; like:

use FindBin;
use lib "$FindBin::Bin/../lib";

Upvotes: 14

David W.
David W.

Reputation: 107030

A neat little trick:

#! /usr/bin/env perl

use strict;
use warnings;

BEGIN {
    our $moduleIsMissing;
    eval {
        require My::Module;
    };

    if ($@) {
        $moduleIsMissing = 1;
    }
}

if ($main::moduleIsMissing) {
    print "Module is missing. I've got to do something about it!\n"
}
else {
    print "Module is there. I'm fine!\n";
}

I'm not happy about the $main::moduleIsMissing thing, but I haven't figured a way around it.

If My::Module is available, it's loaded and everything is fine. Otherwise, the $main::moduleIsMissing flag is set. This allows you to test to see if the module was loaded, and if not, take evasive action. For example, your program will use boldfacing when printing text if module Term::Cap is available, but if not, will simply print out the text sans the boldface.


Back to the question: It's much better to do:

use lib "MyDir";

Rather than the @INC.

The use lib includes the directory at compile time. Thus, if I had a module "Foo::Bar" in directory "MyDir", I could do this:

use lib qw(MyDir);
use Foo::Bar;

without Perl complaining. If I did this:

push (@INC, qw(MyDir));
use Foo::Bar;;

Perl would complain it can't find my module.

Upvotes: 1

njsf
njsf

Reputation: 2739

push @INC, "/path/Table.pm";

Does not work because @INC is supposed to be a list of directories, not of full paths to modules. So if you do:

push @INC, "/path";

It should work.

Having said that, use lib "/path"; is also a good option.

Depending on your programs' install directory structure using the FindBin to determine the real location of your script may prove useful to construct the correct path to your module.

Upvotes: 4

Related Questions