What is the difference between the perl -n
and perl -p
options?
What is a simple example to demonstrate the difference?
How do you decide which one to use?
How do you decide which one to use?
You use -p
if you want to automatically print the contents of $_
at the end of each iteration of the implied while
loop. You use -n
if you don't want to print $_
automatically.
An example of -p
. Adding line numbers to a file:
$ perl -pe '$_ = "$.: $_"' your_file.txt
An example of -n
. A basic grep
replacement.
$ perl -ne 'print if /some search text/' your_file.txt
-p
is short for -np
, and it causes $_
to be printed for each pass of the loop created by -n
.
perl -ne'...'
executes the following program:
LINE: while (<>) {
...
}
while
perl -pe'...'
executes the following program:
LINE: while (<>) {
...
}
continue {
die "-p destination: $!\n" unless print $_;
}
See perlrun for documentation about perl
's command-line options.
What is the difference between the perl -n and perl -p options?
-p
causes each line to be printed; equivalent to:
while (<>) { ... } continue { print }
-n
does not automatically print each line; equivalent to:
while(<>) {...}
What is a simple example to demonstrate the difference?
eg, replace foo
with FOO
:
$ echo 'foo bar' | perl -pe 's/foo/FOO/'
FOO bar
$ echo 'foo bar' | perl -ne 's/foo/FOO/'
$
How do you decide which one to use?
One example where -n
is useful is when you don't want every line printed, and there is a conditional print in the code, eg, only show lines containing foo
:
$ echo -e 'foo\nbar\nanother foo' | perl -ne 'print if /foo/;'
foo
another foo
$
The command-line options are documented in perlrun documentation
perl -n 等价于 while(<>){...} perl -p 等价于 while(<>){...;print;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.