我不知道這會幫助,但我覺得不得不想出一個在Perl中寫這個的方法。我的意圖是讓Perl運行一個shell腳本,並將它設置的任何shell變量分配給Perl腳本中的類命名變量。
其他是正確的,因爲你「源」的任何shell腳本將在一個子shell中。我想我可以使用「sh -x cmd」來至少讓shell在設置時顯示變量。
這是我寫的:
use strict; use warnings;
our $DATE;
my $sh_script = "./test1.sh";
my $fh;
open($fh, "sh -x '$sh_script' 2>&1 1>/dev/null |") or die "open: $!";
foreach my $line (<$fh>) {
my ($name, $val);
if ($line =~ /^\+ (\w+)='(.+)'$/) { # Parse "+ DATE='/bin/date;'
$name = $1;
($val = $2) =~ s{'\\''}{'}g; # handle escaped single-quotes (eg. "+ VAR='one'\''two'")
} elsif ($line =~ /^\+ (\w+)=(\S+)$/) { # Parse "+ DATE=/bin/date"
$name = $1;
$val = $2;
} else {
next;
}
print "Setting '$name' to '$val'\n" if (1);
# NOTE: It'd be better to use something like "$shell_vars{$name} = $val",
# but this does what was asked (ie. $DATE = "/bin/date")...
no strict 'refs';
${$name} = $val; # assign to like-named variable in Perl
}
close($fh) or die "close: ", $! ? $! : "Exit status $?";
print "DATE: ", `$DATE` if defined($DATE);
有一定更多的錯誤檢查你可以這樣做,但是這並獲得成功對我來說,如果你想趕上是shell變量。
爲什麼你不想爲此使用Perl的日期時間模塊? – ghostdog74 2010-09-09 10:43:10
@ ghostdog74你甚至不需要一個模塊。標量上下文中的'localtime'函數產生一個幾乎相同的字符串:'perl -le'print scalar localtime'',你只需要得到時區並且它們是相同的。 – 2010-09-09 10:54:26
嘿日期只是一個例子...它可以是任何東西在日期的地方(ls,chown,echo .....)在第一個文件中,我需要向perl發送什麼命令; – raghu 2010-09-16 11:43:16