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

查看:183
本文介绍了默认情况下,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天全站免登陆