Veltro has asked for the wisdom of the Perl Monks concerning the following question:
I found out that I left some unaltered code that I programmed 10 years ago and it went unnoticed. I knew this bug and I actually fixed it quick and dirty in multiple places but I never found a good fix for it.
What is the best way to use the splice inside of a loop like this (foreach, or other)
Original code bugged:
sub filterExclude{ my $ar = $_[0] ; # REF! my $someConfig = $_[1] ; my $ix = 0 ; foreach ( @{$ar} ) { my $sKey = $_ ; if ( exists ( $someConfig ->{ $sKey }->{ Exclude} ) && $someConf +ig ->{ $sKey }->{ Exclude} ) { splice ( @{$ar}, $ix, 1 ) ; $ix = $ix - 1 ; } $ix = $ix + 1 ; } }
Right now I have:
sub filterExclude{ # 20240414 Quick fix needed because of the splice my $ar = $_[0] ; # REF! my $someConfig = $_[1] ; my $tmpCheckedEverything = 0 ; while ( !($tmpCheckedEverything) ) { $tmpCheckedEverything = 1 ; my $ix = 0 ; foreach ( @{$ar} ) { my $sKey = $_ ; if ( exists ( $someConfig ->{ $sKey }->{ Exclude} ) && $someC +onfig ->{ $sKey }->{ Exclude} ) { splice ( @{$ar}, $ix, 1 ) ; $tmpCheckedEverything = 0 ; } $ix = $ix + 1 ; } }
But of course this is ugly and not efficient
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to use a splice inside a foreach
by hv (Prior) on Apr 13, 2024 at 11:14 UTC | |
by Veltro (Hermit) on Apr 18, 2024 at 14:04 UTC | |
|
Re: How to use a splice inside a foreach
by tybalt89 (Monsignor) on Apr 13, 2024 at 17:40 UTC | |
|
Re: How to use a splice inside a foreach
by LanX (Saint) on Apr 13, 2024 at 09:01 UTC | |
|
Re: How to use a splice inside a foreach
by The_Dj (Scribe) on Apr 18, 2024 at 02:18 UTC |