-p是的缩写-np,它导致$_为每个创建的循环打印-n.
perl -ne'...'
Run Code Online (Sandbox Code Playgroud)
执行以下程序:
LINE: while (<>) {
...
}
Run Code Online (Sandbox Code Playgroud)
而
perl -pe'...'
Run Code Online (Sandbox Code Playgroud)
执行以下程序:
LINE: while (<>) {
...
}
continue {
die "-p destination: $!\n" unless print $_;
}
Run Code Online (Sandbox Code Playgroud)
有关命令行选项的文档,请参阅perlrunperl.
你如何决定使用哪一个?
您可以使用-p,如果你想自动打印的内容,$_在隐含的每次迭代结束while循环.您可以使用-n,如果你不希望打印$_自动.
一个例子-p.将行号添加到文件:
$ perl -pe '$_ = "$.: $_"' your_file.txt
Run Code Online (Sandbox Code Playgroud)
一个例子-n.基本的grep替代品.
$ perl -ne 'print if /some search text/' your_file.txt
Run Code Online (Sandbox Code Playgroud)
perl -n 和 perl -p 选项有什么区别?
-p导致打印每一行;相当于:
while (<>) { ... } continue { print }
Run Code Online (Sandbox Code Playgroud)
-n不自动打印每一行;相当于:
while(<>) {...}
Run Code Online (Sandbox Code Playgroud)
有什么简单的例子可以证明差异?
例如,替换foo为FOO:
$ echo 'foo bar' | perl -pe 's/foo/FOO/'
FOO bar
$ echo 'foo bar' | perl -ne 's/foo/FOO/'
$
Run Code Online (Sandbox Code Playgroud)
您如何决定使用哪一个?
有用的一个例子-n是,当您不想打印每一行,并且代码中有条件打印时,例如,仅显示包含以下内容的行foo:
$ echo -e 'foo\nbar\nanother foo' | perl -ne 'print if /foo/;'
foo
another foo
$
Run Code Online (Sandbox Code Playgroud)
命令行选项记录在perlrun 文档中