FreeKB - Remove empty lines from an array in Perl
Remove empty lines from an array in Perl

Home > Search


Let's say you have an array of data that contains empty lines, like this.

Hello

World


How
are

you

 

The following markup can be used to remove the empty lines from the array. The \S regular expression means "anything except for a whitespace". It may also be noteworthy that \s means "whitespace", thus \S is the opposite of \s.

@array = grep /\S/, @array;

 

Which will result in the array having no empty lines, like this.

Hello
World
How
are
you

 


Looping through array

If you are looping through the array, something like this should get the job done.

foreach my $line (@array) {

  $line =~ s|^\s*$||g;

}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter d3d24 in the box below so that we can be sure you are a human.




Comments