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?
Use compact_blank to remove empty strings from Arrays and Hashes.
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 .
grep
the output so you only get entries that contain non-whitepace characters.
my @plain = grep { /\S/ } split(/\n/,$plaintext);
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:
Loop through the array @plain
, making $_
set to current array element
foreach(@plain){
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. ''
If the current element passes those checks push it to @new
push(@new, $_);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With