我拥有一个其他模块调用的perl子例程。有一个shell脚本setjavaenv.sh和一个批处理脚本setjavaenv.bat,用于设置环境变量JAVA_HOME。 现在我需要使用setjavaenv.sh设置的JAVA_HOME从我的子例程调用java程序。有没有办法在不编写新的shell / bat脚本(可能会打印值)的情况下执行此操作?
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");
}
答案 0 :(得分:3)
my $javaHome = `. setjavaenv.sh; echo -n $JAVA_HOME`;
答案 1 :(得分:1)
是的,您可以使用反引号运算符从子进程获取环境。
#!/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
}
然后您可以这样称呼它:
run_with_envs( source => "envs.sh",
commandline => "echo \$FOO" ,
envs => [ "FOO" ] );
对于您的计划,它将是:
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"; }