user175008
user175008

Reputation:

Getting in a perl program environment variable set by a shell script

I own a perl subroutine which some other module calls. There is a shell script setjavaenv.sh and a batch script setjavaenv.bat which sets the environment variable JAVA_HOME. Now I need to invoke a java program from my subroutine using the JAVA_HOME set by setjavaenv.sh. Is there a way to do this without writing a new shell/bat script(which perhaps prints the value)?

my subroune {
 #system("setjavaenv.sh")  #Doesn't work since it probably spawns a new env.
 my $javaHome = $ENV{JAVA_HOME};
 system("$javaHome/bin/java MyProgram");
}

Upvotes: 0

Views: 4323

Answers (2)

IanNorton
IanNorton

Reputation: 7282

Yes, You can use the backtick operator to get en environment from a sub process.

#!/usr/bin/perl

sub run_with_envs {
        my %args = @_; # use a hash for function params
        my $source_envs = $args{source};
        my $cmdline = $args{commandline};
        my @varnames = @{$args{envs}};

        foreach my $vname ( @varnames ){
                print "## reading $vname\n";
                $ENV{$vname} = `source $source_envs; echo -n \$$vname`;
        }

        print "## running command : $cmdline\n";
        my $rv = system($cmdline) / 256;
        return $rv; # program exited successfully if rv == 0
}

You can then call it like so:

run_with_envs( source => "envs.sh",
               commandline => "echo \$FOO" ,
               envs => [ "FOO" ] );

For your program it would be:

run_with_envs( source => "setjavaenv.sh",
               commandline => "\$JAVA_HOME/bin/java MyProgram" ,
               envs => [ "JAVA_HOME","PATH" ], );
if ( $rv != 0 ){ die "program exited with state $rv"; }

Upvotes: 1

ysth
ysth

Reputation: 98388

my $javaHome = `. setjavaenv.sh; echo -n $JAVA_HOME`;

Upvotes: 3

Related Questions