I have a file named file with three lines:
line one
line two
line three
When I do this:
perl -ne 'print if /one/' file
I get this output:
line one
when i try this:
perl -pe 'next unless /one/' file
the output is:
line one
line two
line tree
I expected the same output with both one-liner. Are my expectations wrong or is wrong something else?
Your expectation is wrong. The -p
switch puts the following loop around your code:
LINE:
while (<>) {
... # your program goes here
} continue {
print or die "-p destination: $!\n";
}
If you read the documentation for next
, it says:
Note that if there were a
continue
block on the above, it would get executed even on discarded lines.
next
actually jumps to the continue block (if any), before it goes back to the loop's condition.
You could do something like
perl -pe '$_ = "" unless /one/' file