For some cases, it will be faster to not move all of the elements down each time:

my $o= 0; for my $i ( 0..$#$av ) { if( should_keep($i) ) { $av->[$o++]= $av->[$i]; } } $#$av= $o-1;

        - tye
#!/usr/bin/perl -w use strict; my @prime= qw( 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ); my %prime; @prime{@prime}= (1)x@prime; sub one { my $av= [ 0..100 ]; my $o= 0; for my $i ( 0..$#$av ) { if( $prime{$i} ) { $av->[$o++]= $av->[$i]; } } $#$av= $o-1; return $av; } sub for { my $av= [ 0..100 ]; for my $i ( reverse 0 .. $#$av ) { splice( @$av, $i, 1 ) if ! $prime{$i}; } return $av; } sub whl { my $av= [ 0..100 ]; my $i= @$av; while( 0 <= --$i ) { splice( @$av, $i, 1 ) if ! $prime{$i}; } return $av; } printf "(%s)\n", join " ", @{&one()}; printf "(%s)\n", join " ", @{&for()}; printf "(%s)\n", join " ", @{&whl()}; use Benchmark qw( cmpthese ); cmpthese( -3, { one => \&one, for => \&for, whl => \&whl, } ); __END__ Rate whl for one whl 2610/s -- -63% -78% for 7049/s 170% -- -41% one 11986/s 359% 70% --

In reply to (tye)Re: What's the idiom for finding and removing the found @ARRAY element? by tye
in thread What's the idiom for finding and removing the found @ARRAY element? by John M. Dlugosz

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.