This is a little bit of a question but it may just be a feature request.

Is there a way to, from within a foreach, drop the element you are working with from the array.

Example: @moo = (1 .. 10); foreach (@moo) { if ($_ % 2 > 0) { DROP();} # <----- is what I would LOVE # to do }

Such that the result would be @moo would be (2,4,6,8,10)

Yes I know I can there are all sorts of ways to get the same effect.

Grep: @moo = grep {($_ % 2 > 0)?0:1;} @moo; Or easier to add more complex code if you: @moo = grep {; {if ($_ % 2 > 0){ 0; last; } 1;}} @moo; # PS why do I need that first ';' - I don't know but I do For Loop: for (my $i=0;$i<@moo;$i++) { if ($moo[$i] % 2 > 0) {splice @moo, $i, 1;} } # wow is this slow

But here is what I dislike - the inefficiency of having to use temporary variables or reassaining an entire list.

If a grep could work in place that would be the answer - but it can't. That pretty much doubles the amount of time it takes to work on the array - the assignment back to the original list.

Why is this important to me? I often find myself working with huge arrays. I would love to prune the data in a simple - yet readable away.


In reply to Foreach for array pruning? by spandox

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.