我试图在Perl单行内打印单引号时遇到了这个问题。我最终发现你必须用'\''
来逃避它们。这里有一些代码来说明我的问题。
让我们从打印文本文件开始。
perl -ne 'chomp; print "$_\n"' shortlist.txt
red
orange
yellow
green
blue
现在让我们为每行打印文件的名称。
perl -ne 'chomp; print "$ARGV\n"' shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
然后我们可以在每行添加单引号。
perl -ne 'chomp; print "'$_'\n"' shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
等待,没有工作。让我们再试一次。
perl -ne 'chomp; print "'\''$_'\''\n"' shortlist.txt
'red'
'orange'
'yellow'
'green'
'blue'
所以我现在就开始工作了。但是我仍然对“$ _”为什么要评估程序名称感到困惑。也许这是一件容易的事,但有人可以解释或链接到一些文档?
编辑:我在Red Hat运行的Perl 5.8.8 5
在你的第三个例子中,$ _在引号之外,这意味着它在字符串形成之前被赋值并传递给'perl -ne' – njzk2
这是一个shell特性,与Perl无关。试试'echo foo; echo $ _'(在我的bash或sh上重复两次'foo':'$ _'是最后一个参数)。所以重要的问题是:你在用什么外壳? – amon
我正在使用bash。 – chilemagic