Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Removing empty string elements from an Array

by broquaint (Abbot)
on Nov 13, 2001 at 15:32 UTC ( [id://125028]=note: print w/replies, xml ) Need Help??


in reply to Removing empty string elements from an Array

Having not seen it listed, here's yet another way to do it
my @arr1 = ("foo", "", "bar", "", "baz"); my @arr2 = grep $_, @arr1; { $" = ', '; print "@arr1\n@arr2\n"; }
Since this tests for each element in a boolean context, it will ignore any element perl considers to be false, which includes empty strings (""). However this also has the pitfall of dropping stuff you might want to keep e.g qw(0 1 2) --> (1 2).
That was the more "perlish" way to do it, but if you're determined to use a loop try this
my @arr1 = ("foo", "", "bar", "", "baz"); my @arr2; foreach (@arr1) { push @arr2, $_ if $_ ne ''; }

HTH

broquaint

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://125028]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-04-16 14:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found