加载模块时 perl 的包含路径中的搜索顺序是什么

发布于 2024-12-18 23:54:07 字数 267 浏览 0 评论 0原文

假设 @INC 中有三个路径:path1path2path3。在每个路径下,都有一个名为 foo.pm 的模块。如果我现在通过 use foo; 在我的脚本中加载 foo.pm,那么实际上会加载哪个 foo.pm ?或者换句话说,perl 在 @INC 中搜索路径的顺序是什么?

Let's say there are three paths in @INC: path1, path2 and path3. Under each of these paths, there is a module named foo.pm. If I now load foo.pm in my script via use foo;, which of the foo.pms is actually going to be loaded? Or in other words, what is perl's search order for paths in @INC?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

数理化全能战士 2024-12-25 23:54:07

perldoc -v %INC 显示选择的路径:

use Data::Dumper; 
print Dumper(\%INC);

或者...

perl -Mfoo -e 'print $INC{"foo.pm"}'

require 显示一些隐含搜索顺序的伪代码:

foreach $prefix (@INC) {
}

因此,path1会首先被搜索。

perldoc -v %INC shows which path was chosen:

use Data::Dumper; 
print Dumper(\%INC);

Or...

perl -Mfoo -e 'print $INC{"foo.pm"}'

require shows some psuedo-code which implies the search order:

foreach $prefix (@INC) {
}

Thus, path1 would be searched first.

风追烟花雨 2024-12-25 23:54:07

路径1、路径2、路径3。 Perl 将加载 path1/foo.pm

你为什么会期望它是其他的?

看看 perlfunc perlvar,我可以看到它们不没有明确这么说,但他们确实说:

数组 @INC 包含 do EXPR 、 require 或 use 结构查找其库文件的位置列表。

我认为那里的提示是列表。期望从头到尾处理列表是很正常的。

您可以将此代码放在 use foo; 语句之前:

BEGIN { say "\@INC=(${\join( ', ', @INC )})"; }

如果仍然显示 @INC=(/path1, /path2, /path3) 则将此代码在 use 语句之后:

BEGIN { say "\$INC{'foo.pm'}=$INC{'foo.pm'}"; }

如果该语句仍然显示 $INC{'foo.pm'}=/path3/foo.pm,那么我认为您没有指定您的搜索路径以及您可能的搜索路径。您可能认为您在指定为“/path1”的同一目录中有 foo.pm,但很可能您的某些路径混乱了。

path1, path2, path3. And perl will load path1/foo.pm.

Why would you expect it to be any other?

Looking at perlfunc perlvar, I can see that they don't explicitly say this, but they do say:

The array @INC contains the list of places that the do EXPR , require, or use constructs look for their library files.

I think the hint on there is list. It's unexceptional to expect a list to be processed first-to-last.

You could probably put this code, right before your use foo; statement:

BEGIN { say "\@INC=(${\join( ', ', @INC )})"; }

If that still shows you @INC=(/path1, /path2, /path3) then put this after the use statement:

BEGIN { say "\$INC{'foo.pm'}=$INC{'foo.pm'}"; }

And if that one still shows $INC{'foo.pm'}=/path3/foo.pm, then I think you're not specifying your search paths as well as you might. You might think you have foo.pm in the same directory specified as '/path1', but the likelihood is that you've got some path messed up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文