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:
KEY
VALUE
Like this:
JAVA_HOME 
/opt/java/jdk1.6.0_12
JBOSS_HOME
/opt/java/4.2.3.GA/jboss-as\
Note: I still don't know a lot of PERL.

Script(file: my_setenv.pl ):
$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;
  $iterator++;
 }else{
  print "Setting ENV -> $current_var = $line";
  $ENV{"$current_var"} = $line;  
  $current_var = "";
  $iterator = 0;
 }
}
close(FILE); 

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

That's all.