2

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.

1
  • Put Perl into paragraph mode. Set $/ to an empty string.
    – Dave Cross
    Feb 29, 2012 at 13:47

3 Answers 3

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

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.

1
  • +1 for '$/ = q()' ... you made me look it up in perldoc perlvar. Feb 29, 2012 at 4:26
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.