No one has yet explained why this doesn't work as you expect.

Consider an array of three values:

my @to_clean = ( '', 1, 2 );

We'll loop through the array with indices. We'll make sure that the element at that position is defined, true, and not the empty string:

for my $i ( 0 .. $#to_clean ) { next if defined $to_clean[ $i ] and $to_clean[ $i ]; next unless $to_clean[ $i ] eq ''; }

Here's where it gets tricky. By spliceing, you're changing the original array.

splice( @to_clean, $i, 1 );

After the first loop, we'll splice out the empty string at index zero. The array will then contain 1 and 0 2. Unfortunately, $i will be 1 on the next loop iteration, and it won't check the 0th element again.

You could mess with redo. You could push the elements you want to keep on a secondary array. It's unlikely you'll come up with anything simpler or faster than grep though.

Update: This lets undef through, but it catches zero. It's just an example, though.


In reply to Re: Array Cleaning by chromatic
in thread Array Cleaning by Anonymous Monk

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.