简体   繁体   English

如何忽略perl中的多个换行符?

[英]How do I ignore multiple newlines in perl?

Suppose I have a file with these inputs: 假设我有一个包含这些输入的文件:

line 1


line 2

line3

My program should only store "line1", "line2" and "line3" not the newlines. 我的程序应该只存储“line1”,“line2”和“line3”而不是换行符。 How do I achieve that? 我如何实现这一目标? My program already removed leading and trailing whitespaces but it doesn't help to remove newline. 我的程序已经删除了前导空格和尾随空格但是删除换行符没有帮助。 I am setting $/ as \\n because each input is separated by a \\n. 我将$ /设置为\\ n因为每个输入用\\ n分隔。

while (<>) {
    chomp;
    next unless /\S/;
    print "$_\n";
}

Set

 $/ = q();  # that's an empty string, like "" or ''
 while (<>) { 
      chomp;
      ...
 }

The special value of the defined empty string is how you tell the input operator to treat one or more newlines as the terminator (preferring more), and also to get chomp to remove them all. 定义的空字符串的特殊值是如何告诉输入操作符将一个或多个换行符视为终止符(更喜欢更多),以及让chomp将它们全部删除。 That way each record always starts with real data. 这样每条记录总是以真实数据开始。

Perl -n is the equivalent of wrapping while(<>) { } around your script. Perl -n相当于在脚本周围包裹while(<>){}。 Assuming that all you need to do is eliminate blank lines, you can do it like this: 假设您需要做的就是消除空行,您可以这样做:

#! /usr/bin/perl -n
print unless ( /^$/ );

... On the other hand, if that's all you need to do, you might as well ditch perl and use ......另一方面,如果这就是你需要做的全部,你也可以放弃perl并使用它

grep -n '^$'

Edit: your post says that you want to store values where lines are not blank... in that case, assuming that you don't have too much work to do in the rest of your script, you might do something like this: 编辑:你的帖子说你要存储行不为空的值...在这种情况下,假设你在其余的脚本中没有太多的工作要做,你可能会这样做:

#! /usr/bin/perl -n
my @values;
push @values, $_ unless ( /^$/ );

END {
    # do whatever work you want to do here
}

... but this quickly reaches a point of limiting returns if you have very much code inside the END{} block. ...但是如果你在END {}块中有很多代码,这很快就会达到限制回报的程度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM