简体   繁体   English

Perl命令行脚本和shell变量:如何报价?

[英]Perl command-line script and shell variables: How to quote?

I have a shell script (csh) calling Perl like this: 我有一个调用Perl的shell脚本(csh),如下所示:

set SHELL_VAR = "foo"
set RES = `perl -e 'my $perl_var = uc("$SHELL_VAR"); print "$perl_var\n"'`
echo $RES

I did not manage to use single or double quotes properly, no matter which combination I tried. 无论我尝试哪种组合,我都无法正确使用单引号或双引号。

How do I properly mix variables in Perl and shell? 如何在Perl和Shell中正确混合变量?

Both are starting with $ . 两者都以$开头。 Double quotes use variable values, but returns 双引号使用变量值,但返回

error perl_var: Undefined variable. 错误perl_var: Undefined variable.

in shell. 在外壳中。 Enclosing a Perl script by single quotes led to an empty result. 用单引号将Perl脚本括起来会导致结果为空。 Escaping like \\$perl_var does not succeed either. \\$perl_var这样的转义也不会成功。

You are trying to insert the value of a shell var into a Perl literal of a program that's in a command line. 您正在尝试将shell var的值插入命令行中程序的Perl文字中。 That's two levels of escaping! 这是两个级别的转义! Instead, just pass it to Perl as an argument. 相反,只需将其作为参数传递给Perl。

% set SHELL_VAR = "foo"
% set RES = `perl -e'print uc($ARGV[0])' "$SHELL_VAR"`
% echo "$RES"
FOO

Doh! 卫生署! It's not quite right. 这不太正确。

csh% set SHELL_VAR = foo\"\'\(\ \ \ \$bar
csh% set RES = `perl -e'print uc($ARGV[0])' "$SHELL_VAR"`
csh% echo "$RES"
FOO"'( $BAR

I should get 我应该得到

FOO"'(   $BAR

In sh , I'd use RES="` ... `" aka "$( ... ") , but I don't know the csh equivalent. sh ,我将使用RES="` ... `" aka "$( ... ") ,但我不知道csh等效项。 If someone could fix the above so multiple spaces are printed, I'd appreciate it! 如果有人可以解决上述问题,所以可以打印多个空格,我将不胜感激!

sh$ shell_var=foo\"\'\(\ \ \ \$bar
sh$ res="$( perl -e'print uc($ARGV[0])' "$shell_var" )"
sh$ echo "$res"
FOO"'(   $BAR

You can push your SHELL_VAR into the environment and let Perl pull it from there: 您可以将SHELL_VAR推入环境,然后让Perl从那里拉出来:

#!/bin/csh
setenv SHELL_VAR "foo"
set RES = `perl -e 'my $perl_var = uc($ENV{SHELL_VAR}); print "$perl_var\n"'`
echo $RES

Note that the setenv command lacks the expicit '=' for assignment. 请注意, setenv命令缺少用于分配的显式“ =”。 The environmental variable is availab e to Perl from the %ENV hash with the variable name as its key. 环境变量可以从%ENV哈希中获取到,并且以变量名称为其键。

I found another solution, you can simply concatenate several expressions, ie you can write 我找到了另一个解决方案,您可以简单地连接多个表达式,即可以编写

set XYZ = "foo"`date`bar$HOST'gugus'

for example. 例如。 This is a concatenation of 这是一个串联

foo + `date` + bar + $HOST + gugus

Thus the following works: 因此,以下工作原理:

set SHELL_VAR = "foo"
set RES = `perl -e 'my $perl_var = uc("'$SHELL_VAR'"); print "$perl_var\n"'`
echo $RES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM