How to change @INC to find Perl modules in non-standard locations

http://perlmaven.com/how-to-change-inc-to-find-perl-modules-in-non-standard-locations

问题:

自己写的或者下载安装的module没有放在standard location ,如a module called My::Module saved in /home/foobar/code/My/Module.pm.

如果一个Perl脚本使用此模块,直接use My::Module; 则报错:

Can't locate My/Module.pm in @INC (@INC contains:。。。)

解释:

When perl encounters use My::Module; it goes over the elements of the built-in @INC array that contains directory names. In each directory it checks if there is a subdirectory called "My" and if in that subdirectory there is a file called "Module.pm".

The first such file it encounters will be loaded into memory.

If it does not find the file you get the above error messages.

@INC is defined when perl is compiled and it is embedded in the binary code. You cannot change that, unless you recompile perl. Not something we would do every day.

Luckily the @INC array can be changed in several ways when we execute a script. 

解决:

1.PERLLIB5 (推荐)or PERLLIB

  ~/.bashrc 

  export PERL5LIB=/home/foobar/code(例子)

2. use lib

  Adding a use lib statement to the script will add the directory to @INC for that specific script. Regardless who and in what environment runs it.

    use lib '/home/foobar/code';

    use My::Module;

3. -I on the command line

  temporary solution. perl -I /home/foobar/code script.pl 

  This will add /home/foobar/code to the beginning of @INC for this specific execution of the script.

So which one to use?

If you would like to just test a newer version of a module, I'd recommend the command line flag: perl -I /path/to/lib.

If you are installing lots of modules in a private directory then I'd probably use PERL5LIB though we'll also see local::lib that does this for you.

use lib is used in two cases:

  1. When you have a fixed, but not standard company-wide environment in which you put modules in a common standard location.
  2. When you are developing an application and you'd like to make sure the script always picks up the modules relative to their own location. We'll discuss this in another post.
原文地址:https://www.cnblogs.com/tina-ma/p/4312570.html