如何将 $SHELL 变量传递给 perl 搜索并替换 [英] How do I pass $SHELL variable into a perl search and replace
问题描述
我有以下两个命令:
value=`grep -o Logs\/.*txt\" textFILE`
perl -i -wpe's/" onclick="img=document\.getElementById\('\''img_1'\''\); img\.style\.display = \(img\.style\.display == '\''none'\'' \? '\''block'\'' : '\''none'\''\);return false"/$value/' textFILE
然而,我不断得到一个 Use of uninitialized value $value in concatenation (.) or string at -e line 1, <>第 56 行.
错误.谁能告诉我我做错了什么.
However, I keep on getting a Use of uninitialized value $value in concatenation (.) or string at -e line 1, <> line 56.
error. Can someone tell me what I am doing wrong.
推荐答案
例如:
$ value=$(uname -r)
$ perl -e 'print "$value"'
当我们在这里运行 Perl 来执行我们的代码时,我们不会将 shell 变量 $value 的内容发送给 Perl.我们正在发送文字字符串$value",然后 Perl 将尝试打印该字符串,并打印不存在的 Perl 变量 $value.
When we run Perl to execute our code here we are not sending the contents of the shell variable $value to Perl. We are sending the literal string '$value', which Perl will then try and print the Perl variable $value, which does not exist.
您可以通过以下两种方法纠正此问题.
Here are two ways that you could correct this.
第一个是用双引号而不是单引号包裹你的 Perl 代码,这样在发送到 Perl 时,$value 就变成了 shell 变量 $value 的内容,而不是文字字符串 '$value':
The first would be to wrap your Perl code in double quotes instead of single quotes so that $value becomes the contents of the shell variable $value instead of the literal string '$value' when sent to Perl:
$ value=$(uname -r)
$ perl -e "print '$value'"
3.13.9-generic
但是,当使用这种方法时,如果你有 Perl 变量和这个 shell 变量,你将需要转义"Perl 变量,否则你会得到这样的错误:
However when using this method if you have Perl variables along with this shell variable you will need to 'escape' the Perl variables or you'll get an error like this:
$ value=$(uname -r)
$ perl -e "$example = 'test'; print \"$value $example\";"
syntax error at -e line 1, near "="
使用 \'s 可以纠正这个问题:
Using \'s will correct this:
$ value=$(uname -r)
$ perl -e "\$example = 'test'; print \"$value \$example\";"
3.13.9-generic test
其次,您可以通过将值"导出到环境中,然后通过 Perl 程序中已经可用的 %ENV 哈希访问它来避免将单引号更改为双引号(http://perldoc.perl.org/Env.html).例如:
Secondarily, you can avoid changing the single quotes to double quotes by exporting "value" to the environment, and then accessing it through the %ENV hash already available inside your Perl program (http://perldoc.perl.org/Env.html). For example:
$ export value=$(uname -r)
$ perl -e 'print "$ENV{value}\n"'
3.13.9-generic
请注意您的环境,不要意外覆盖某些所需的环境变量.使用非常特定于您的工作的命名约定会有所帮助:
Be mindful of your environment that you do not accidentally overwrite some needed environment variable. Using a naming convention very specific to your work can help:
$ export MYPROGRAMNAME_KERNEL_VERSION=$(uname -r)
$ perl -e 'print "$ENV{MYPROGRAMNAME_KERNEL_VERSION}\n"'
3.13.9-generic
大多数 Linux 系统上的
printenv
会向您显示当前建立的环境变量.您也可以使用 Perl 来检查 %ENV.
printenv
on most Linux systems will show you the current established environment variables. You could also just use Perl to inspect %ENV.
这篇关于如何将 $SHELL 变量传递给 perl 搜索并替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!