On Tue, Feb 8, 2011 at 9:25 AM, 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.

Hi Yossi,
1. Why not just call the external utility directly using the full path
to it? E.g.:
system('/new/path/to/use/externalUtility');

2. Why not just modify $ENV{'PATH'}? Why do you feel the need to
revert the change?

3. Finally, here's a sub (first line stolen from Gaal's reply) which
does what you want, except since $ENV{'PATH'} is just a string, I
didn't bother saving the original value or using "local" - instead I
just remove the added string after I'm finished with it. The code
assumes Linux PATH conventions, if you need portability Gabor's advise
seems good.

sub launch_external {
    my($new_path, $code) = @_;

    $new_path = ":$new_path";

    $ENV{'PATH'} .= $new_path;
    system($code);
    $ENV{'PATH'} =~ s/\Q$new_path\E$//;

}

# example usage:
launch_external('/new/path/to/use' , 'externalUtility');

One comment - you'll notice in both (1) and (3) I used "system"
instead of back-ticks that you used. The reason is  I don't see in
your example that you are using the return value and if you don't,
it's better to use "system" - it makes it clearer you are running an
external command and not trying to capture its output.

Regards,
Offer
_______________________________________________
Perl mailing list
Perl@perl.org.il
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to