Perl使用/需要绝对路径?

时间:2013-02-13 13:38:39

标签: perl absolute-path

如果我有一个.pm文件,我有没有办法use,而不会将其放在@INC路径上?我认为在我的特定用例中会更清楚 - 比使用相对路径或将此目录添加到@INC更清晰。

修改:澄清:

我希望避免必须遍历@INC中的每个项目,而是直接指定我感兴趣的文件。例如,在Node.JS中,require('something')将搜索列表路径,但require('/specific/something')将直接进入我告诉的地方。

在Perl中,我不确定这是否与require中的功能相同,但似乎有效。

但是,use语句需要裸字。这让我对如何进入绝对路径感到有点困惑。

5 个答案:

答案 0 :(得分:5)

您可以使用:

use lib '/path/to/Perl_module_dir'; # can be both relative or absolute
use my_own_lib;

你可以自己修改@INC(暂时,不要害怕,这也是use lib也是如此):

BEGIN{ @INC = ( '/path/to/Perl_module_dir', @INC ); } # relative or absolute too
use my_own_lib;

答案 1 :(得分:4)

根据评论中的讨论,我建议使用require本身。如下所示,

require "pathto/module/Newmodule.pm";

Newmodule::firstSub();

您还可以使用以下其他选项

  • use lib 'pathto/module';此行需要添加到您要使用该模块的每个文件中。
  

使用lib'pathto / module';
  使用Newmodule;

  • 使用PERL5LIB环境变量。使用导出在命令行上设置此项,或将其添加到~/.bashrc,以便每次登录时都会将其添加到@INC。记住PERL5LIB在所有@INC目录之前添加目录。所以它将首先使用。您也可以使用

    在apache httpd.conf中进行设置
    SetEnv PERL5LIB /fullpath/to/module
    
  • 或者将其设置在BEGIN块中。

答案 2 :(得分:1)

一般来说,设置PERL5LIB环境var。

export PERL5LIB=/home/ikegami/perl/lib

如果要查找的模块要安装在相对于脚本的目录中,请使用以下命令:

use FindBin qw( $RealBin );
use lib $RealBin;
  # or
use lib "$RealBin/lib";
  # or
use lib "$RealBin/../lib";

这将正确处理脚本的符号链接。

$ mkdir t

$ cat >t/a.pl
use FindBin qw( $RealBin );
use lib $RealBin;
use Module;

$ cat >t/Module.pm
package Module;
print "Module loaded\n";
1;

$ ln -s t/a.pl

$ perl a.pl
Module loaded

答案 3 :(得分:0)

您可以使用Module::Load模块

use Module::Load;
load 'path/to/module.pm';

答案 4 :(得分:0)

FindBin::libs可以解决问题:

# search up $FindBin::Bin looking for ./lib directories
# and "use lib" them.

use FindBin::libs;
相关问题