问题描述
我想从my_perl.pl"调用env.sh"而不分叉子shell.我尝试过像这样的 backtics 和系统 --> system (. env.sh)
[dot space env.sh] ,但是不起作用.
I want to call "env.sh " from "my_perl.pl" without forking a subshell. I tried with backtics and system like this --> system (. env.sh)
[dot space env.sh] , however wont work.
推荐答案
子环境不能改变父环境.最好的办法是从 Perl 代码中解析 env.sh
并在 %ENV
中设置变量:
Child environments cannot change parent environments. Your best bet is to parse env.sh
from inside the Perl code and set the variables in %ENV
:
#!/usr/bin/perl
use strict;
use warnings;
sub source {
my $name = shift;
open my $fh, "<", $name
or die "could not open $name: $!";
while (<$fh>) {
chomp;
my ($k, $v) = split /=/, $_, 2;
$v =~ s/^(['"])(.*)\1/$2/; #' fix highlighter
$v =~ s/\$([a-zA-Z]\w*)/$ENV{$1}/g;
$v =~ s/`(.*?)`/`$1`/ge; #dangerous
$ENV{$k} = $v;
}
}
source "env.sh";
for my $k (qw/foo bar baz quux/) {
print "$k => $ENV{$k}\n";
}
给定
foo=5
bar=10
baz="$foo$bar"
quux=`date +%Y%m%d`
打印
foo => 5
bar => 10
baz => 510
quux => 20110726
代码只能处理简单的文件(例如,它不处理if
语句或foo=$(date)
).如果您需要更复杂的东西,那么为您的 Perl 脚本编写一个包装器,首先获取 env.sh
是正确的方法(这也可能首先是正确的方法).
The code can only handle simple files (for instance, it doesn't handle if
statements or foo=$(date)
). If you need something more complex, then writing a wrapper for your Perl script that sources env.sh
first is the right way to go (it is also probably the right way to go in the first place).
在执行 Perl 脚本之前获取 env.sh
的另一个原因是,在 Perl 中设置环境变量对于希望看到它们的模块来说可能太晚了.
Another reason to source env.sh
before executing the Perl script is that setting the environment variables in Perl may happen too late for modules that are expecting to see them.
在文件foo
中:
#!/bin/bash
source env.sh
exec foo.real
其中 foo.real 是您的 Perl 脚本.
where foo.real is your Perl script.
这篇关于如何在不分叉子shell的情况下在perl脚本中获取shell脚本[环境变量]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!