Dexter
Dexter

Reputation: 1337

Importing environment variables set by batch file in parent Perl script

I am writing a cross-platform build script in Perl for code compilation.

In Windows, I need to execute vsvars32.bat to set the environment variables:

sub set_win_env {
      #MSVC version 9.0 is installed
      $VS90COMNTOOLS = $ENV{'VS90COMNTOOLS'};
      $VS90COMNTOOLS .= "vsvars32.bat"
      if($VS90COMNTOOLS ne "") {
          system("$VS90COMNTOOLS");
      }
 }

The environment variables set by executing the batch files gets lost as interpreter spawns another shell to execute the batch file.

How can I import those variables in the parent Perl script?

Upvotes: 0

Views: 2161

Answers (2)

choroba
choroba

Reputation: 241988

If your BAT file is simple (i.e. it only contains lines of the form VAR=VALUE), you can parse it by Perl. If there is something more going on (some values are calculated from others etc.), just output all the variable names and their values at the end of the BAT script in the form VAR=VALUE.

The parsing of the simple format is easy:

while (<$BAT>) {
    chomp;
    my ($var, $val) = split /=/, $_, 2;
    $ENV{$var} = $val;
}

Upvotes: 1

cdarke
cdarke

Reputation: 44394

As you say, using system will set the environment variables in the child process, not in the current process. The problem is that you have a file in '.bat' format, which is a different language to Perl (OK, maybe calling it a language is a bit strong).

You need to either parse the file yourself and translate it into Perl, or, run your perl from a .bat file which has (for example):

CALL "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" amd64
perl perlscript.pl

Upvotes: 1

Related Questions