tags:

views:

74

answers:

3

Hello! 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?

+1  A: 
$ perl -ne 'next unless /one/ && print' file
line one
ghostdog74
+2  A: 

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.

codaddict
+8  A: 

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
cjm