Hi Uri! Some notes.
On Wed, 12 Apr 2017 15:19:33 -0400 Uri Guttman <u...@stemsystems.com> wrote: > On 04/12/2017 03:00 PM, David Emanuel da Costa Santiago wrote: > > Hello! > > > > What's the best way to delete multiple indices from an array? > > > > i'm doing: > > > > --------------- > > my @array=qw/zero one two three four five six seven eight nine ten/; > > > > my @indicesToDelete = (2,4,6,7); > > if you have the indexes to keep, this would be a simple slice: > > my @keep_indexes = ( 0, 1, 3, 5, 8,9 10 ); > @array = @array{ @keep_indexes } ; > it should be «@array = @array[ @keep_indexes ] ;» instead. With curly braces it's a hash slice. > so one idea is to make that list of kept indexes from the list of > indexes to delete: > > my %keep_hash ; > @keep_hash{ 0 .. 10 } = () ; # no need for any values so this save space > delete @keep_hash{ @keep_indexes } ; > @array = @array{ keys %keep_hash } ; 1. again - square brackets instead of curly braces. 2. You should sort the keys numerically using sort { $a <=> $b }. 3. Better use « keys@array» or in older perls «0 .. $#array» to avoid hard coding the values and magic constants. ============ some other ways I can think of doing it: 1. my %blacklist; @blacklist{@remove} = (); @array = @array[grep {!exists $blacklist{$_} } keys@array]; 2. my @new; while (my ($i, $v) = each@array) { if (@remove and $i == $remove[0]) { shift@remove; } else { push @new, $v; } } @array = @new =========== https://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it Regards, Shlomi Fish > > > > my %hash; > > > > @hash{(0..scalar(@array)-1)} = @array; > > > > delete $hash{$_} for @indicesToDelete; > delete can be used on a slice > > delete @hash{ @indicesToDelete } ; > > uri > > Perl Guru for hire. Available for contract/full time/part time Perl hacking. > -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/