如何将我的 Bash 循环变量传递给 Perl 解释器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8974493/
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
How can I pass on my Bash loop variable to the Perl interpreter?
提问by Zaid
I'm trying to modify some scripts with a combination of Bash and Perl. The trouble is that Perl thinks that $indexis its own variable, which is never defined:
我正在尝试使用 Bash 和 Perl 的组合来修改一些脚本。问题是 Perl 认为这$index是它自己的变量,从未定义过:
for index in {1..25}; do
perl -pi -e 's/\d+/$index/' cmd_$index.sh;
done
Is there a way to make $indexwear its Bash cloak within the Perl one-liner?
有没有办法$index在 Perl one-liner 中穿上它的 Bash 斗篷?
回答by daxim
Squeeze an export index;in the doloop. Refer to $ENV{index}in the body of the Perl program.
export index;在do循环中挤压一个。$ENV{index}在 Perl 程序体中引用。
Alternatively: Use the double quotes "… $index … "to interpolate the shell variable into the expression that makes up the body of the Perl program. In case you want to expand this one-liner, take care to properly escape Perl expressions, such as $on variable names, and perhaps backslashes, so that are interpreted by Perl, not the shell.
或者:使用双引号"… $index … "将 shell 变量插入到构成 Perl 程序主体的表达式中。如果您想扩展这一单行,请注意正确转义 Perl 表达式,例如$变量名和反斜杠,以便由 Perl 解释,而不是由 shell 解释。
回答by dgw
Use "instead of '. The bash can then substitute the variable before perl sees it.
使用"代替'。然后 bash 可以在 perl 看到它之前替换该变量。
回答by Kyle Jones
Use double quotes instead of single quotes and $index will be interpolated before the -e string is passed to Perl.
使用双引号代替单引号,$index 将在 -e 字符串传递给 Perl 之前插入。
回答by wmorrison365
Here's a working example (though not in the terms of your problem - sorry!):
这是一个有效的例子(虽然不是你的问题 - 对不起!):
generatep() {
perl -e '
$_stem=$ARGV[0];
$_ctx=$ARGV[1];
$_role=$ARGV[2];
$i=$ARGV[3];
$ct=$i + $ARGV[4];
while ($i < $ct) {
print "user=$_stem$i,$_ctx,$_role\n";
$i++;
}
' ${stem} ${ctx} ${role} ${startix} ${count}
}
回答by TLP
I guess the problem here is that the bash shell globs do not support ranges. For some reason, I thought they did. No matter, perl supports ranges just fine:
我想这里的问题是 bash shell globs 不支持范围。出于某种原因,我认为他们做到了。没关系,perl 支持范围就好了:
perl -pi -e '
BEGIN { @ARGV = map "cmd_$_.sh", 1 .. 25; }
my ($index) = $ARGV =~ /(\d+)/;
s/\d+/$index/'
A little bit clumsy, but it's all one language anyway.
有点笨拙,但无论如何都是一种语言。

