March 23, 2010

Setting environment variables with perl

Usually I work with different environments on different projects, this means that sometimes I have to change system variables and references in order to work in a different project. To avoid this repetitive task, I've created a few PERL scripts to make my life easier.

Changing environment variables

What I did was to create a script that receives as a parameter a file name, this file contains a set of environment variables to set. To make it even easier, the file has the format:
Like this:
Note: I still don't know a lot of PERL.

Script(file: ):
$filename = $ARGV[0];
print "Using filename $filename";

open FILE, "$filename" or die $!;

$iterator = 0;
$current_var = "";
while (my $line = ) {

 if( $iterator == 0 ){
  $current_var = $line;
  print "Setting ENV -> $current_var = $line";
  $ENV{"$current_var"} = $line;  
  $current_var = "";
  $iterator = 0;

print "Let's show all ENVIRONMENT variables.\n";
foreach $key (keys(%ENV)) {
    printf("%-10.10s: $ENV{$key}\n", $key);
$> perl google_code_env.env

That's all.