in reply to How to use a splice inside a foreach

The usual way to cope with the array changing while you iterate over it is to go in reverse, so that the splice does not affect any not-yet-processed index. It's easiest to iterate over the index rather than the value:

for my $ix (reverse 0 .. $#$ar) { if ($someConfig->{ $ar->[$ix] }{Exclude}) { splice @$ar, $ix, 1; } }

Another approach is to fully replace the contents of the arrayref using a grep:

@$ar = grep !$someConfig->{$_}{Exclude}, @$ar;

Replies are listed 'Best First'.
Re^2: How to use a splice inside a foreach
by Veltro (Hermit) on Apr 18, 2024 at 14:04 UTC

    Sorry for the late reply, for some reason perlmonks was not responding for days.

    Thanks, hv, tybalt89, LanX and The_Dj for your great suggestions, I can use one of these.

    PS, indeed, the exists was wrong as well. not exists ( $someConfig->{$_} ) was supposed to prevent the autovivication of the key in $someConfig.