Taking your solutions one by one:

@n = grep $_, @n;

This will put into @n all elements of the original @n that evaluate to true. But that means that elements whos value is 0, or "", or anything else that evaluates to false, will get skipped over. "undef" does evalute to false, by the way.

@n = grep defined, @n

This is what you want if all you care about is getting rid of elements whos value is undef. This will retain elements of zero value or empty strings, so long as they're not undef. I worked up several test snippets showing that this works for that type of situation. No need to show them here; it's pretty basic stuff.

@n = grep defined and length, @n

Here you're getting into trouble because of the low precedence of the "and" logical short circuit operator. You would be better served by using "&&" in this case. "and" binds at such a low precedence that everything to its right is no longer seen as part of the parameter list to grep. Wierd, huh? "&&" solves this problem (parenthesis placed in the right place would solve it too). But then you're going to be saying "if its value is defined and of a length greater than zero". That may be ok, or it might be better to say "@n = grep defined && $_, @n;". That way instead of testing for length, you're testing for truth.

And I won't get into the rest of your solutions because they are too unPerlish to wade through. I think that in general you'll find it to be a good way to run amok; to try to delete array elements while iterating through the array with a C-style loop.


Dave


In reply to Re: Removing null values from within an array by davido
in thread Removing null values from within an array by coldfingertips

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.