One problem is modifying the size of an array while iterating over it with a foreach loop is unhealthy. If we were programming in C++ one would say that the splice invalidates the iterator. We don't have such well defined terminology for what you're doing, in Perl. But the effect is similar.

Additionally, even if this did work as you intended, you're doing way too much work. To splice out an element within an array, all elements to the right need to shift leftward one. So each and every splice is a linear operation. And the general algorithm of filtering an array using a loop and splice will have quadratic growth. If you're willing to trade memory for speed, a better solution is one that populates a new array (even if internally) with the elements filtered from the original array. This sort of algorithm has a linear order of growth as the array's size grows.

Not only is this better algorithm an order of magnitude faster, it's also far easier to write, especially since that's what the Perl built-in grep function does just that:

my @array = ( 'stuff', '', 'stuff', '', '10', '', '-', '' ); @array = grep { $_ ne '' } @array;

If you want to remove all elements that have either an empty string, or are not defined, you could just do this:

@array = grep length, @array;

This works because length returns a false value for empty strings, as well as for containers that are 'undef'.

my @array = ( 'stuff', '', 'stuff', '', '10', '', '-', '' );

So on the first iteration


Dave


In reply to Re: Unable to remove items from an array that are empty ' ' by davido
in thread Unable to remove items from an array that are empty ' ' by nat47

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.