何时调用@INC 中的子程序引用? [英] When is a subroutine reference in @INC called?
问题描述
正如标题所说,我不清楚何时会调用这样的子程序.来自 require 页面,位于 perldoc 可以这样写:
As the title says, I'm not clear on when such a subroutine will be called. From the require page at perldoc one can write:
push @INC, &my_sub;
sub my_sub {
my ($coderef, $filename) = @_; # $coderef is &my_sub
...
}
但是这到底是哪里呢?需要的包还是需要的脚本(或包)?我已经用一些哨兵 print
语句尝试了这两种方法,但都没有效果很明显,有些东西我没有得到.
but where does this go exactly? The required package or the requiring script (or package)? I've tried both with some sentinel print
statements but neither worked so clearly there is something I'm not getting.
推荐答案
Perl在遍历@INC
寻找模块时调用@INC
中的子程序引用.也就是说,当您尝试使用 use
或 require
加载模块并且 Perl 在前面的 @INC中找不到该模块时,您将触发它代码>位置.
Perl calls a subroutine reference in @INC
when it is traversing @INC
to look for a module. That is, you'll trigger it when you try to load a module with use
or require
and Perl does not find that module in the preceding @INC
locations.
BEGIN {
push @INC,
sub { print "Oops: There was an error looking for $_[1]
"; };
}
eval "use Cat::Burglar";
eval "use Local::NotThere";
require Cat::Burglar;
在尝试加载模块之前,您需要确保您的子程序引用在 @INC
中.请记住,use
是一个编译时特性,而 require
是一个运行时特性.与添加其他常规"@INC
条目一样,您可能希望尽早在程序中的 BEGIN
块中执行此操作.
You need to ensure that your subroutine reference is in @INC
before you try to load the modules. Remember that use
is a compile time feature and that require
is a run time feature. As with adding other "regular" @INC
entries, you probably want to do it in a BEGIN
block as early as possible in your program.
这篇关于何时调用@INC 中的子程序引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!