为什么是“$ _”在一个Perl一行程序一样$ ARGV? [英] Why is '$_' the same as $ARGV in a Perl one-liner?
问题描述
我就遇到了这个问题,同时试图一个Perl的一个班轮打印单引号。我终于想通了,你有来逃避他们'\\''
。下面是一些code来说明我的问题。
I ran into this problem while trying to print single quotes in a Perl one-liner. I eventually figured out you have to escape them with '\''
. Here's some code to illustrate my question.
让我们先从打印的文本文件。
Let's start with printing a text file.
perl -ne 'chomp; print "$_\n"' shortlist.txt
red
orange
yellow
green
blue
现在让我们来打印文件的名称,而不是为每一行。
Now let's print the name of the file instead for each line.
perl -ne 'chomp; print "$ARGV\n"' shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
然后,我们可以在每行加单引号。
Then we can add single quotes around each line.
perl -ne 'chomp; print "'$_'\n"' shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
shortlist.txt
等待,没有工作。让我们再试一次。
Wait that didn't work. Let's try again.
perl -ne 'chomp; print "'\''$_'\''\n"' shortlist.txt
'red'
'orange'
'yellow'
'green'
'blue'
所以我现在的工作。但我为什么$ _计算程序名称仍然感到困惑。也许这是一件很容易,但有人可以解释或链接到一些文档?
So I got it working now. But I'm still confused on why '$_' evaluates to the program name. Maybe this is something easy but can someone explain or link to some documentation?
编辑:我在Red Hat 5上运行的Perl 5.8.8
edit: I'm running Perl 5.8.8 on Red Hat 5
推荐答案
要你的shell,格格;打印'$ _的'\\ n'''/ code>后的字符串这是并置
To your shell, 'chomp; print "'$_'\n"'
results in a string that's the concatenation of
-
格格;打印
(单引号里面的第一个序列), - 的变量
$ _
的值, -
\\ n
(单引号内的第二序列)。
chomp; print "
(the first sequence inside single quotes),- the value of its variable
$_
, and \n"
(the second sequence inside single quotes).
在庆典
, $ _
...扩展到最后一个参数previous命令膨胀后......。由于这恰好是 shortlist.txt
,被传递到 perl的
以下内容:
In bash
, $_
"... expands to the last argument to the previous command, after expansion. ...". Since this happens to be shortlist.txt
, the following is passed to perl
:
chomp; print "shortlist.txt\n"
例如,
$ echo foo
foo
$ echo 'chomp; print "'$_'\n"'
chomp; print "foo\n"
这篇关于为什么是“$ _”在一个Perl一行程序一样$ ARGV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!