Reputation: 25117
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?
Upvotes: 5
Views: 674
Reputation: 62099
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
Upvotes: 11
Reputation: 454990
First about the options used in the programs:
-n assume "while (<>) { ... }" loop around program
-p assume loop like -n but print line also, like sed
.
perl -ne 'print if /one/' file
prints only the first line as its the only line having the string "one" in it.
perl -ne 'next unless /one/' file
will not print anything because it has no call to print and no -p
option.
perl -pe 'next unless /one/' file
Almost same as above there is no output from the program itself but because of the -p
option, every line of the file is printed.
Upvotes: 2