Removing empty elements from an array

In my Perl code, I am accessing an email. I need to get a table in it and parse it in an array. I did this using:

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

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

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

+7
source share
4 answers

grep output so that you only get entries containing non-white characters.

 my @plain = grep { /\S/ } split(/\n/,$plaintext); 
+14
source

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

Fast and dirty if you are not ready to fix your split:

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

edit: how does it work

There will be more elegant and effective ways to do this than the above, but, like anything else, perl-y tmtowtdi! How it works:

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

    foreach(@plain){

  • Check the current item to see if we are interested in it:

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

  • If the current item passes these checks, click it on @new

    push(@new, $_);

+4
source

This is what I used, too late, but it's good, can be used in the future

 $t = "1.2,3.4,3.12,3.18,3.27"; my @to = split(',',$t); foreach $t ( @to ){ push ( @valid , $t ); } my $max = (sort { $b <=> $a } @valid)[0]; print $max 
0
source

Your code requires one line addition and it works

  @plain= grep { $_ ne '' } @plain; 
0
source

All Articles