lackita has asked for the wisdom of the Perl Monks concerning the following question:

Hey, monks. I've got two module trees which are nearly identical, and I have to run the same command once with each of these trees. The best method I can come up with is to combine a local $ENV{PERL5LIB} with system:

#/usr/bin/perl for my $tree ("a","b") { local $ENV{PERL5LIB} = $tree; system("perl -e 'use Foo;Foo::Bar()'"); }

Is there a way to accomplish this without having to start a subprocess?

Replies are listed 'Best First'.
Re: Changing Module Tree
by wind (Priest) on Apr 05, 2011 at 20:28 UTC

      Alright, so that solves the problem of a single module, but what if Foo uses several other modules?

      Also, this would work in the limited example, but I also have a third module path that will need to be restored afterwards:

      #/usr/bin/perl use Foo; Foo::Prep(); for my $tree ("a","b") { local $ENV{PERL5LIB} = $tree; delete $INC{'Foo.pm'}; require Foo; Foo::Bar(); } Foo::Cleanup();

      It seems cumbersome to have to stick an additional delete/require after the loop.

        Save the state of the %INC before the loop, and restore it at the beginning of each iteration.

        Something as simple as this might work, assuming %INC isn't a tied hash:

        %INC = %old_INC;
        Or alternatively:
        for (keys %INC) { delete $INC{$_} if ! $old_INC{$_}; }