perl - 为什么我的 -p one-liner 打印出我想跳过的行?

标签 perl

我有一个名为 file 的文件,包含三行:

line one
line two
line three



当我这样做时:

perl -ne 'print if /one/' file



我得到这个输出:

line one



当我尝试这个时:

perl -pe 'next unless /one/' file



输出是:

line one
line two
line tree



我期望两个单行的输出相同。我的期望是错误的还是其他错误?

最佳答案

你的期望是错误的。 -p switch 在您的代码周围放置以下循环:

LINE:
  while (<>) {
      ...             # your program goes here
  } continue {
      print or die "-p destination: $!\n";
  }

如果您阅读 the documentation for next , 它说:

Note that if there were a continue block on the above, it would get executed even on discarded lines.


next实际上跳转到continue block (如果有的话),在它回到循环的条件之前。

你可以做类似的事情
perl -pe '$_ = "" unless /one/' file

关于perl - 为什么我的 -p one-liner 打印出我想跳过的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2395570/

相关文章:

perl - 使用ssh在远程服务器上执行内联脚本时保护管道字符

php - 天花板函数的 PHP 代码

perl - 在@ISA 上使用拼接在 perl 5.12.2 中是否存在问题?

regex - 使用 Regex 转义单引号字符串中的所有双引号

perl - 将 Word doc 或 docx 文件转换为文本文件?

c - 查找 C 代码中的错误

xml - 如何使用 Perl 的 XML::Simple 从 XML 文件中提取值?

perl - 从 BEGIN block 中调用 Perl fork

regex - 什么正则表达式可以匹配相同字符的序列?

perl - 如何使用固定连接条件建立 DBIx::Class 关系?