If your indexes are sorted, you could keep a separate counter for the number of items removed and subtract it from $i when splicing.

However, it's much easier and more efficient to create a new array instead of splicing the same array, since each splice needs to copy all the elements from $i to the end of the array rearrange/copy the pointers to the elements from element $i to the end of the array.

my @newarray; foreach my $i (@arrayindex) { push @newarray,$array[$i]; }
Depending on your algorithm, you could probably do that at the same time/instead of building the @arrayindex array.

Another way would be to use grep (if you can determine which elements to keep based solely on their value):

my @kept = grep { $_ < 4 and $_ > 10 } @array;
or even
@array = grep { $_ < 4 and $_ > 10 } @array;

In reply to Re: Remove array elements dynamically! by Joost
in thread Remove array elements dynamically! by newbio

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.