Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing blank elements from an array

Tags:

regex

perl

In my Perl code, I am accessing an email. I need to fetch the table in it and parse it into an array. I did it using:

my @plain = split(/\n/,$plaintext);

However, there are many blank elements in @plain. It has 572 elements and about half of them are empty.

Am I doing anything wrong here? What do I need to add/change in my code to get rid of the blank elements?

like image 721
Rahul Desai Avatar asked Jul 06 '12 14:07

Rahul Desai


People also ask

How do you remove empty elements from an array in Ruby?

Use compact_blank to remove empty strings from Arrays and Hashes.

Can you have an empty element in an array?

To check if an array contains empty elements call the includes() method on the array, passing it undefined as a parameter. The includes method will return true if the array contains an empty element or an element that has the value of undefined .


2 Answers

grep the output so you only get entries that contain non-whitepace characters.

my @plain = grep { /\S/ } split(/\n/,$plaintext);
like image 115
Dave Cross Avatar answered Oct 24 '22 00:10

Dave Cross


The correct way to do it is here from @dave-cross

Quick and dirty if you're not up for fixing your split:

foreach(@plain){
    if( ( defined $_) and !($_ =~ /^$/ )){
        push(@new, $_);
    }
}

edit: how it works

There are going to be more elegant and efficient ways of doing it than the above, but as with everything perl-y tmtowtdi! The way this works is:

  1. Loop through the array @plain, making $_ set to current array element

    foreach(@plain){

  2. Check the current element to see if we're interested in it:

    ( defined $_) # has it had any value assigned to it !($_ =~ /^$/ ) # ignore those which have been assigned a blank value eg. ''

  3. If the current element passes those checks push it to @new

    push(@new, $_);

like image 42
beresfordt Avatar answered Oct 23 '22 23:10

beresfordt