Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "perl -n" and "perl -p"?

Tags:

perl

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?

like image 289
Rob Bednark Avatar asked Sep 05 '16 04:09

Rob Bednark


Video Answer


2 Answers

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
like image 122
Dave Cross Avatar answered Oct 14 '22 07:10

Dave Cross


-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.

like image 41
ikegami Avatar answered Oct 14 '22 07:10

ikegami