@INC中的子例程引用何时被调用? [英] When is a subroutine reference in @INC called?

查看:87
本文介绍了@INC中的子例程引用何时被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我不清楚何时会调用此类子例程.从要求页中"rel =" noreferrer> 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.

推荐答案

当遍历@INC查找模块时,Perl在@INC中调用子例程引用.也就是说,当您尝试使用userequire加载模块而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屋!

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