Using lib pragma after explicitly setting @INC has no effect

use feature qw(say);
use strict;
use warnings;
BEGIN {
    @INC = qw(dir1 dir2); # <-- lib pragma works fine if I omit this line
    # @INC = ();  <-- this is what I wanted to do
    use lib 'dir3';
}
say for @INC;

      

Output

dir1
dir2

      

Expected Output :

dir3
dir1
dir2

      

+3


source to share


2 answers


Operator

A is use

contained in an implicit block BEGIN

and all Perl blocks BEGIN

in the program are executed as soon as they finish compiling

This means that there are nested blocks here BEGIN

, but because the inner - the operator use lib 'dir3'

- finishes compilation at the end of the statement, it is executed first. It is followed by the closing parenthesis of the explicit block BEGIN

, which ends this block compilation, and only then these statements are executed

Here is an example program that uses only operators say

and replaces the use

original operator with an explicit blockBEGIN

use strict;
use warnings;
use feature 'say';

BEGIN {

    say "outer BEGIN";

    BEGIN {
        say "inner BEGIN";
    }
}

      

Output

inner BEGIN
outer BEGIN

      



Your code works as if you wrote it like this

use feature qw(say);
use strict;
use warnings;

use lib 'dir3';

BEGIN {
    @INC = qw(dir1 dir2);
}

say for @INC;

      

So, it first executes use lib

by adding dir3

in @INC

and then the explicit block is executed BEGIN

and overwrites @INC

at all

If you want to remove first @INC

and then add instructions to it use lib

, then you should write

BEGIN {
    our @INC = ( );
}

use lib 'dir3';

      

Without nesting, blocks BEGIN

are executed in the order shown in the program

+9


source


From perldoc - lib

It is a small, simple module that makes it easy to manipulate @INC at compile time.

When you insert say for @INC;

after opening parenthesis and before assignment like

BEGIN {
    say for @INC;
    @INC = qw(dir1 dir2); # <-- lib pragma works fine if I omit this line
    # @INC = ();  <-- this is what I wanted to do
    use lib 'dir3';
}

      

You will see dir3

.




And perldoc - use states

Since the usage takes effect at compile time, it does not respect normal flow control of compiled code.

dir3

inserted into @INC

before doing anything else and then @INC

assigned a new value ( dir1, dir2

). You see this new assigned value when you finally look at @INC

.

-1


source







All Articles