Robert Hegner
Robert Hegner

Reputation: 9396

Set environment variables by batch file called from perl script

Let's consider the following perl script:

#!/usr/bin/perl
system("C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/Common7/Tools/VsDevCmd.bat");
system("msbuild");

The batch file invoked with the first system call is supposed to set up some environment variables so that the msbuild executable in the second system call can be found.

When I run this perl script I get the following error:

'msbuild' is not recognized as an internal or external command, operable program or batch file.

So it looks like the environment variables set in the batch file are not made available to the context of the perl script. What can I do to make this work?

Note 1

Running first the batch file from a console window and then running msbuild works fine. So the batch file works as expected and msbuild is actually available.

Note 2

My real-world perl script is much longer. This example here is a massive simplification which allows to reproduce the problem. So I cannot easily replace the perl script with a batch file, for example.

Note 3

The funny thing is: I've been using this perl script for one or two years without any problems. Then suddenly it stopped working.

Upvotes: 0

Views: 814

Answers (1)

Dave Cross
Dave Cross

Reputation: 69314

  • 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.

Upvotes: 4

Related Questions