When is a subroutine reference in @INC called?

后端 未结 2 2078
温柔的废话
温柔的废话 2020-12-10 15:27

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         


        
相关标签:
2条回答
  • 2020-12-10 15:41

    To avoid confusing our subroutine with the subroutines in the standard Perl modules generally it is good to use the unshift instead of push. So it will first use your subroutine from the @INC.

    0 讨论(0)
  • 2020-12-10 15:54

    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;
    

    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.

    0 讨论(0)
提交回复
热议问题