简体   繁体   中英

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. 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.

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. That way each record always starts with real data.

Perl -n is the equivalent of wrapping while(<>) { } around your script. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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