How do I remove all undefs from array?
Asked Answered
O

1

19

While reading from a configuration file in Perl there might be cases when a line is invalid and it does not need to get added to my array of valid lines. Since I'm using a for loop here, even the invalid lines create an undef entry. How can I remove all them afterwards?

Thanks!

Oliy answered 20/6, 2012 at 15:31 Comment(1)
if you're creating the config file use a module like Config::Simple. If you're reading the content of a pre-existing config file into an array why are you pushing invalid entries into your array instead of skipping them?Bessel
D
56
@array = grep defined, @array;
Doris answered 20/6, 2012 at 15:40 Comment(4)
simple and great solutionInutile
It's working for me. Thank you for this simple solution.Babbler
Interesting, I am seeing defined(@array) is deprecated at /path/to/script.pl line X. using perl 5.10.1 (yes I realize the year is 2021, but I gotta work with what I got)Narbada
Should have added this immediately, but @array = grep {defined} @array; works for my particular flavor of Perl.Narbada

© 2022 - 2024 — McMap. All rights reserved.