bash 在 Perl 程序中访问 shell 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6964536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:31:39  来源:igfitidea点击:

Accessing shell variable in a Perl program

linuxperlbash

提问by Ankur Agarwal

I have this Perl script:

我有这个 Perl 脚本:

#!/usr/bin/perl

$var = `ls -l $ddd` ;
print $var, "\n";

And ddd is a shell variable

ddd 是一个 shell 变量

$ echo $ddd
arraytest.pl

When I execute the Perl script I get a listing of all files in the directory instead of just one file, whose file name is contained in shell variable $ddd.

当我执行 Perl 脚本时,我会得到目录中所有文件的列表,而不仅仅是一个文件,其文件名包含在 shell 变量 $ddd 中。

Whats happening here ? Note that I am escaping $ddd in backticks in the Perl script.

这里发生了什么事 ?请注意,我在 Perl 脚本中以反引号转义 $ddd。

回答by Keith Thompson

The variable $dddisn't set *in the shell that you invoke from your Perl script.

该变量$ddd未在您从 Perl 脚本调用的 shell 中设置 *。

Ordinary shell variables are not inherited by subprocesses. Environment variables are.

子进程不会继承普通 shell 变量。环境变量是。

If you want this to work, you'll need to do one of the following in your shell before invoking your Perl script:

如果你想让它工作,你需要在调用你的 Perl 脚本之前在你的 shell 中执行以下操作之一:

ddd=arraytest.pl ; export ddd # sh

export ddd=arraytest.pl       # bash, ksh, zsh

setenv ddd arraytest.pl       # csh, tcsh

This will make the environment variable $dddvisible from your Perl script. But then it probably makes more sense to refer to it as $ENV{ddd}, rather than passing the literal string '$ddd'to the shell and letting it expand it:

这将使$ddd您的 Perl 脚本中的环境变量可见。但是,将它称为 可能更有意义$ENV{ddd},而不是将文字字符串传递'$ddd'给 shell 并让它展开它:

$var = `ls -l $ENV{ddd}`;

回答by mu is too short

You forgot to export ddd:

你忘了export ddd

Mark each name to be passed to child processes in the environment.

标记要传递给环境中的子进程的每个名称。

So dddis not automatically available to child processes.

因此ddd不会自动对子进程可用。

回答by Jacek Kaniuk

The hash %ENVcontains your current environment.

散列%ENV包含您当前的环境。

$var = `ls -l $ENV{ddd}`;

/edit - it works, checked, of course ddd need to be exported before running script

/edit - 它可以工作,已检查,当然在运行脚本之前需要导出 ddd

export ddd='arraytest.pl'
perl script.pl