Sam Weisenthal
Sam Weisenthal

Reputation: 2951

Iteratively delete elements from array

I have an array, @cuts, of indices of the elements that I would like to remove from @Data. Is this an appropriate way to do so?

foreach (@cuts){

    $Data[$_] = "NULL";

}


for my $i (0 .. $#Data){
    if ($Data[$i] eq "NULL"){
        splice(@Data,$i,1);
        } 
}

Upvotes: 1

Views: 70

Answers (3)

ikegami
ikegami

Reputation: 385897

You don't need to use a sentinel value ("NULL").

my %cuts = map { $_ => 1 } @cuts;
my @keeps = grep !$cuts{$_}, 0..$#Data;
@Data = @Data[@keeps];

This can surely be simplified by merging it with the preceding code.

Upvotes: 3

user2752322
user2752322

Reputation: 71

my @newData = grep { !/^NULL\z/ } @Data;

Upvotes: 2

RobEarl
RobEarl

Reputation: 7912

Combining @toolic and @user2752322:

delete @Data[@cuts];
my @newData = grep { defined } @Data;

Upvotes: 2

Related Questions