Setting an Environment Variable Through a Perl Script

How to export environment variable set in perl script to batch shell?

Changes to environment variables can not effect the parent process, it's part of how they work, so nothing you do in the Perl script can change the environment variables of the batch script. However any child process, started with exec(), system() or `` will see the changes you made in the Perl script.

How do I set an environment variable in Perl?

You can do it like this:

$ENV{HOME} = 'something different';

But please note that this will only have an effect within the rest of your script. When your script exits, the calling shell will not see any changes.

As perldoc -v %ENV says:

%ENV The hash %ENV contains your current environment. Setting a value in "ENV" changes the environment for any child processes you subsequently "fork()" off.

Set environment variables by batch file called from perl script

  • Your process has an associated environment which contains things like the search path.
  • When a sub-process starts, the new process has a new, separate, environment which starts as a copy of the parent process's environment.
  • Any process (including sub-processes) can change their own environment. They cannot, however, change their parent's process's environment.
  • Running system() creates a new environment.

So when you call system() to set up your environment, it starts a new sub-process with a new environment. Your batch program then changes this new environment. But then the sub-process exits and its environment ceases to exist - taking all of the changes with it.

You need to run the batch file in a parent process, before running your Perl program.

How to Share ENV Variables Among Perl Scripts

In general, child processes inherit a separate copy of the environment from their parent and changes made by the child do not propagate to the parent's environment.
Env::Modify offers a workaround for this issue implementing the "shell magic" that the perlfaq talks about.

Typical usage:

use Env::Modify 'system',':bash';

print $ENV{FOO}; # ""
system("export FOO=bar");
print $ENV{FOO}; # "bar"
...
print $ENV{GIT_FLOW_ERROR_MSG}; # ""
system("unpushed-changes");
print $ENV{GIT_FLOW_ERROR_MSG}; # "true"
...


Related Topics



Leave a reply



Submit