views:

2519

answers:

3

I need to set the an environment variable from within Perl. Ideally, I need to query a variable and then change it if it is not what is required. Specifically it is the PATH variable I want to change.

Can someone tell me how to get and set these variables?

+6  A: 

$ENV{PATH}?

Keep in mind that environment variables only affect subprocesses, however. You can't run a Perl program, change %ENV, and then see that change in the parent process -- the environment does not work that way.

jrockway
LOL, we managed to submit the same answer in the same second! :-p
Leon Timmermans
Great minds think alike ;)
jrockway
Ack, that was just what I wanted to do. Thanks for the reply anyway
Xetius
+2  A: 

You can do that using the %ENV hash

$ENV{PATH} = 'C:\\Windows\;D:\\Programs';
Leon Timmermans
+10  A: 

If you need to change environment variables globally and permanently, as if you set it in the control panel, then you have to muck with the registry (update: and now there are modules to do this, Win32::Env and Win32::Env::Path). Note that changing variables in the registry and "broadcasting" the change will not change the environment variables in some current processes, notably perl.exe and cmd.exe.

If you just want to change the current process (and subsequently spawned child processes), then the global %ENV hash variable is what you want (e.g. $ENV{PATH}). See perldoc perlvar.

runrig
See http://search.cpan.org/~adamk/Win32-Env-Path-0.01/lib/Win32/Env/Path.pm for a module that appears to do more or less what was described in that perlmonks node.
oeuftete
Thanks, I didn't know about those modules...and they didn't exist at the time of the perlmonks node.
runrig
That one may have very well inspired by your post... who knows. :) It doesn't look like it includes your step from the PM node to broadcast the update.
oeuftete
That's ok that Win32::Env::Path doesn't broadcast...it makes it easier to mess with the path at least, then you can use Win32::Env to broadcast.
runrig