Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

perl - 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
   ...
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...