On 04/12/2017 04:38 PM, Shlomi Fish wrote:
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.
yes, i missed that.
2. You should sort the keys numerically using sort { $a <=> $b }.
i don't sort the indexes. that was some other code.
3. Better use « keys@array» or in older perls «0 .. $#array» to avoid hard
coding the values and magic constants.
again, that wasn't my code.
============
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
that is a much slower version of your grep solution.
uri
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/