默认情况下,Perl 不包括@INC 中的当前目录吗? [英] Doesn't Perl include current directory in @INC by default?

查看:20
本文介绍了默认情况下,Perl 不包括@INC 中的当前目录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有完全理解 Perl 对包名的解析,但我一直认为以下应该总是有效的,假设您从包含它的目录中执行 myscript.pl:

I have never fully understood Perl's resolution of package names, but I always assumed that the following should always work, assuming you are executing myscript.pl from within the directory that contains it:

myscript.pl (contains the following statement: use Class1::Class2::Class3)
Class1/
    Class2/
        Class3.pm (contains the following package declaration: package Class1::Class2::Class3;)

但是,这在我的代码中不起作用,因为找不到 Class3.pm.看@INC,不包含当前目录,只包含我的Strawberry Perl安装的各个目录.

However, this is not working in my code because Class3.pm cannot be located. Looking at @INC, it does not include the current directory, only various directories of my Strawberry Perl installation.

解决此问题的推荐方法是什么?我想我可以修改@INC,或者我可以开始使用 FindBin,但我不确定哪个最好.我继承了这段代码,只是将它迁移到一个新位置,但看起来旧代码不需要这样的解决方案(我可能是错的,仍在寻找......)

What is the recommended way to solve this? I suppose I could modify @INC, or I could start using FindBin, but I'm not sure which is best. I have inherited this code and am simply migrating it to a new location, but it doesn't look like the old code needed either such solution (I could be wrong, still looking...)

推荐答案

Perl 不会在当前目录中搜索模块,也不会在脚本目录中搜索模块,至少现在不会了.出于安全原因,当前目录在 5.26 中从 @INC 中删除.

Perl doesn't search the current directory for modules or the script's directory for modules, at least not anymore. The current directory was removed from @INC in 5.26 for security reasons.

然而,任何依赖于 @INC 中的当前目录的代码在 5.26 之前都存在漏洞.这样做的代码,就像你的一样,错误地使用当前目录作为脚本目录的代理.这种假设通常是不正确的.

However, any code that relies on the current directory being in @INC was buggy far before 5.26. Code that did so, like yours, incorrectly used the current directory as a proxy for the script's directory. That assumption is often incorrect.

要告诉 Perl 在脚本的目录中查找模块,请使用以下命令:

To tell Perl to look in the script's directory for modules, use the following:

use FindBin 1.51 qw( $RealBin );
use lib $RealBin;

use Cwd qw( abs_path );
use File::Basename qw( dirname );
use lib dirname(abs_path($0));

这篇关于默认情况下,Perl 不包括@INC 中的当前目录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆