【发布时间】:2014-01-24 04:33:34
【问题描述】:
我在尝试在 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 5 上运行 Perl 5.8.8
【问题讨论】:
-
在您的第三个示例中,$_ 在引号之外,这意味着在形成字符串并传递给
perl -ne之前对其进行评估 -
这是一个shell特性,与Perl无关。尝试
echo foo; echo $_(在我的bash 或sh 上重复foo两次:$_是最后一个参数)。所以重要的问题是:您使用的是什么外壳?