in reply to Dynamic "use lib"

Wrap all the statements above the uses in a BEGIN block. Perl does indeed scan the code for "use" statements prior to anything else, because they are implicitly wrapped in BEGIN blocks.

------
We are the carpenters and bricklayers of the Information Age.

Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

I shouldn't have to say this, but any code, unless otherwise stated, is untested

Replies are listed 'Best First'.
Re: Re: Dynamic "use lib"
by samtregar (Abbot) on May 21, 2004 at 17:00 UTC
    That won't work. The compile-time effect of 'use' will not be affected by a run-time 'if' block, even if it's inside a BEGIN. You need to wrap it in an 'eval' inside a BEGIN:

    BEGIN { if ($version =~ /beta/){ eval "use lib('/path/to/dev/modules')"; } else { eval "use lib('/path/to/prod/modules')"; } }

    Or, simpler, just manipulate @INC directly since that's what 'use lib' is doing:

    BEGIN { if ($version =~ /beta/){ unshift @INC, '/path/to/dev/modules'; } else { unshift @INC, '/path/to/prod/modules'; } }

    -sam

      Actually 'use lib' does a little more than just push into @INC (it also considers architecture specific subdirectories) so you may want to use it after all.
      BEGIN { require lib; if ($version =~ /beta/){ lib->import('/path/to/dev/modules'); } else { lib->import('/path/to/prod/modules'); } }
      Now, that makes absolutely no sense. BEGIN blocks are supposed to happen AT compile-time, meaning they happen simultaneous with the use statements.

      Or, does each BEGIN-block get its own BEGIN-CHECK-INIT-END sequence?

      ------
      We are the carpenters and bricklayers of the Information Age.

      Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      I shouldn't have to say this, but any code, unless otherwise stated, is untested

        You're missing the point. The 'use' statement does its thing at compile-time. That means that as soon as Perl compiles a 'use lib' it affects @INC. That's as true inside a BEGIN as it is outside a BEGIN. Here let me demonstrate:

        BEGIN { if (@INC) { use lib '/foo'; } else { use lib '/bar'; } } print "INC IS: @INC\n";

        Running this code you can see that the 'if' did not effect the 'use' statements. That's because 'if' is a run-time operator and 'use' is a compile-time statement. See:

        $ perl begin.pl INC IS: /bar /foo /usr/local/lib/perl5/5.6.1/i686-linux /usr/local/lib +/perl5/5.6.1 /usr/local/lib/perl5/site_perl/5.6.1/i686-linux /usr/loc +al/lib/perl5/site_perl/5.6.1 /usr/local/lib/perl5/site_perl .

        -sam