0

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");
}

2 Answers 2

3
my $javaHome = `. setjavaenv.sh; echo -n $JAVA_HOME`;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I got an alternate answer for linux/shell -- system("sh -c \"source setjavaenv.sh; env;\"") and parse it. However, no clue for bat yet.
1

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"; }

1 Comment

Should use local $ENV{$vname} = ... rather than $ENV{$vname}, as otherwise the value will be set for the parent process permanently as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.