@INC中的子例程引用何时被调用? [英] When is a subroutine reference in @INC called?
问题描述
正如标题所述,我不清楚何时会调用此类子例程.从
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.
推荐答案
当遍历@INC
查找模块时,Perl在@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]\n"; };
}
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屋!