I have an array of strings that comes from data in a hash table. I am trying to remove any (apparently) empty elements, but for some reason there seems to be an obstinate element that refuses to go.
I am doing:
# Get list array from hash first, then
@list = grep { $_ ne ' ' } @list;
@list = uniq @list;
return sort @list;
At the grep line I get the Use of uninitialized value in string ne... message with the rest of the array printed correctly below.
I’ve tried doing it the ‘long’ way:
foreach (@list) {
if ($_ ne ' ') {
push @new_list, $_;
}
}
But this produces exactly the same result. I tried using defined with the expected result (nothing).
I could sort the array beforehand and delete the first element, but that seems very risky as I cannot guarantee that the data set will always have blank elements. It also seems excessive to resort to regular expressions, but perhaps I’m wrong. I’m sure I’m missing something ridiculously simple, as usual.
My answer assumes that you do not want strings that are either empty (meaning undefined or have a length of 0) or consist solely of spaces.
Your
grepline only tests for strings that equal exactly one space. However, the warning implies that at least one array element is indeedundefined. Comparing an undefined value witheqwill only yield true for an empty string, not for a single space.So in order to remove all entries that are either undefined or consist only of spaces you could do something like this:
@list = grep { defined && m/[^\s]/ } @list;Note that an empty space is trueish for Perl. Therefore a simple
grep defined, @listwill actually not throw out the entries that consist solely of spaces.