http://qs321.pair.com?node_id=1083510


in reply to Iterating through an array using multiple loops and removing array elements

I think the splice thing won't work unless you are going backwards through the array (or something) or using first_index from List::MoreUtils to choose what to splice, since removing entries will mess up the significance of the counter value. Why not keep it simple and just push on to an array of 'values to keep' rather than removing values you don't want?

Totally untested example:

my @entries = ...; my $top_entry = shift @entries; my @keepers; for (@entries) { my $comparison = compare_sub( $top_entry, $_ ); if ( $comparison > $user_defined_value ) { push @keepers, $_; } }

Replies are listed 'Best First'.
Re^2: Iterating through an array using multiple loops and removing array elements
by BiochemPhD (Novice) on Apr 24, 2014 at 04:25 UTC
    I've thought about that but the problem is that after I take the zeroth element and compare it to everything else in the array (removing both the zeroth element and any that meet the comparison criteria), I want to then move onto the next remaning element and repeat the process over and over again until the entire list has been consumed.

      What about making a subroutine for the iterative comparison and have it recursively call itself on the kept values from the array unless some condition is true?

      iterate(@entries); sub iterate { my ( $top_entry, @entries ) = @_; my @keepers; for (@entries) { my $comparison = compare_sub( $top_entry, $_ ); if ( $comparison > $user_defined_value ) { push @keepers, $_; } } iterate(@keepers) unless ...; }

      EDIT: A variation where you continue iterating or assign final result depending on some condition. It's hard to know the right approach from here w/o more info

      my @final_result; iterate(@entries); sub iterate { my ( $top_entry, @entries ) = @_; my @keepers; for (@entries) { my $comparison = compare_sub( $top_entry, $_ ); if ( $comparison > $user_defined_value ) { push @keepers, $_; } } if (...) { iterate(@keepers); } else { @final_result = ...; } }
        Recursive iteration through a subroutine might work, but I can't figure out how I would reset the value for $top_entry after one iteration through.