Perl: remove empty elements from array

I have an array with a bunch of empty strings, and other "empty" items, that I want to remove. Perl's grep() command makes this very simple:

@a = ("one", "", "three", "four", 0, "", undef, "eight");

@b = grep($_, @a);

# @b = ("one","three","four","eight");

The first argument to grep is an expression which evaluates whether $_ is a truthy value. This could easily also have been $_ ne "" so we don't also filter out "" and 0.

Leave A Reply - 1 Reply
Replies
hj 2020-11-08 04:32am - No Email - Logged IP: 94.31.80.14

the hint with truthy values is great. good solution!

All content licensed under the Creative Commons License