Is that code an example or is that the specific instance you're trying to replace? Because if the latter, you can just use grep:
my @array = grep $_ != 5, 0..9;
Actually this isn't exactly the same, because your code has a bug, assuming that your goal is to weed out elements equal to 5. (That's the goal, right? If not, never mind.)

The bug is that you're altering the array while progressing through the loop, which means that you skip certain elements. Try your code on this array:

my @array = qw(0 1 2 3 4 5 5 6 7 8 9 );
Only the first 5 will be removed, because after splice-ing out the first 5, the index of the 5 following it has just decreased by 1. But the loop counter increments, and you end up skipping the 5 following it.

As for your general question, which seems to be, is there a way to get rid of reliance on loop counters when iterating through arrays. And that's a good question, and I don't really think there is a good way. There isn't a magic variable for "index into an array" when in a foreach loop. Although perhaps there should be; Dominus has a post about this.

All the same, though, you should probably refrain from altering an array while iterating over it.


In reply to Re: Help me not use codefor($i=0;$i=$#array;$i++)/code...Please! by btrott
in thread Help me not use for($i=0;$i=$#array;$i++)...Please! by IraTarball

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.