in reply to Perl modifying output of an array to remove blank lines

Welcome to the Monastery, namelessjoe,

The following will remove any lines that are empty, or contain only whitespace:

@array = grep { $_ !~ /^(?:\s+|)$/ } @array;

If you want to keep lines that do contain whitespace and nothing else (ie. remove *only* blank lines):

@array = grep { $_ ne '' } @array;

-stevieb

Replies are listed 'Best First'.
Re^2: Perl modifying output of an array to remove blank lines
by namelessjoe (Initiate) on Oct 08, 2015 at 20:00 UTC

    this didn't seem to have any effect i used it like this

    my @Goodlines = $line =~ m/(^\S{1}\/\S{1})\s+\S{7}\s+\S{1}\s+(\-\S{3}\ +.\S{4}\sdBm)\s(\-\S{3}\.\S{4}\sdBm)/g; #this string filters the for +values i want @Goodlines = grep { $_ !~ /^(?:\s+|)$/ } @Goodlines;

      What is in your  @Goodlines array? The code posted by stevieb seems to work exactly as advertised:

      c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my @lines = ('', ' ', ' ', 'x', ' x', 'x ', ' x ', ' x ',); ;; my @no_empties = grep { $_ !~ /^(?:\s+|)$/ } @lines; ;; dd \@no_empties; " ["x", " x", "x ", " x ", " x "]
      Can you put something into the  @lines array that doesn't come out as you want?

      Incidentally, I would prefer an inverse approach to the regex: a non-blank line is one that has at least one non-blank (i.e., non-whitespace, or \S) character in it:

      c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my @lines = ('', ' ', ' ', 'x', ' x', 'x ', ' x ', ' x ',); ;; my @no_empties = grep m{\S}xms, @lines; ;; dd \@no_empties; " ["x", " x", "x ", " x ", " x "]


      Give a man a fish:  <%-{-{-{-<

        I humbly refer you to my previous reply which solves namelessjoe's problem. It works because the @goodlines array is empty on those occasions where the blank lines are output.

        In short, there's no point trying to remove some entries from the array which are themselves empty or just whitespace because there are no entries in the array. The thread title is a bit misleading in that respect. I initially started down the route which you and stevieb took, but a quick test determined that the output would not match what was reported in the original node. Hence the conclusion/supposition that the "bad" lines were ones where the array was entirely empty.

        Hope this helps and that it avoids anybody spending more time on blind alleys.