I suppose you can use a functional idiom to encapsulate this.

# not tested
sub with_path($&) {
  my($new_path, $code) = @_;
  local $ENV{PATH} = $new_path;
  $code->();
}

{
  # ...
  with_path((join $path_sep, $ENV{PATH}, $some_dir), {
    # Code to run with modified path
  });
}


On Tue, Feb 8, 2011 at 11:22 AM, Shlomi Fish <[email protected]> wrote:
> On Tuesday 08 Feb 2011 09:25:22 Yossi Itzkovich wrote:
>> Hi,
>>
>> In one of my scripts I have to launch an external utility, and since it
>> might not be in the user path, I would like to add the target directory
>> (or directories) to the PATH environment.  To be on the safe side, I want
>> to restore the original path after execution of the utility. I thought of
>> using:
>>
>> {
>> local $ENV{PATH}.=":/new/path/to/use";
>> `externalUtility`;
>> }
>>
>> The problem is that I want to do ".=", but at this point (because of
>> "local"), the original value is empty. Is there a trick here to use, or
>> should I do it by saving the old path, setting the new one, restore the
>> old value ?
>
> What I normally do is something like:
>
> local $ENV{PATH} = $ENV{PATH} . ....
>
> You can also do:
>
> {
>        local $ENV{PATH} = $ENV{PATH};
>        $ENV{PATH} .= ...;
> }
>
> Both are a bit ugly, but I think you'll survive.
>
> There are some abstractions for handling PATH and related variables on CPAN
> such as http://search.cpan.org/dist/Env-Path/ . I had a good experience with
> it when I used it in the run-tests.pl script of Freecell Solver, but some
> people on IRC told me it sucked, so your kilometrage may vary.
>
> Regards,
>
>        Shlomi Fish
>
> --
> -----------------------------------------------------------------
> Shlomi Fish       http://www.shlomifish.org/
> Interview with Ben Collins-Sussman - http://shlom.in/sussman
>
> Chuck Norris can make the statement "This statement is false" a true one.
>
> Please reply to list if it's a mailing list post - http://shlom.in/reply .
> _______________________________________________
> Perl mailing list
> [email protected]
> http://mail.perl.org.il/mailman/listinfo/perl
>



-- 
Gaal Yahas <[email protected]>
http://gaal.livejournal.com/
_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to