1

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);
        } 
}
0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I am very confused as to why this works, but this is the best solution. My subroutine was working on a global array (stackoverflow.com/questions/24812456/…), and this was the only one that removed elements not only in the scope of the sub but also in the main scope my @newData = grep { !/^NULL\z/ } @Data; removes them in the sub, but then they get replaced by blanks in the main program...
2

Combining @toolic and @user2752322:

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

3 Comments

undef @Data[@cuts] or @Data[@cuts] = () would be preferable to delete.
@ikegami The documentation for delete warns that its use on array values is deprecated (although I'm admittedly unaware of the current attitude toward it on p5p--the warning may be outdated, it's been around since at least 5.12). Plus it conveys intent better to undef the values you don't want, then grep the remaining defined values.
@Slade, Oops, yeah, was confused because there's no actual harm in using delete on array elements. Using undef on variables, on the other hand, is usually a bad idea unless you specifically intend to defy the optimization it defies. Doesn't matter for a slice, though. Assigning undef (as you unclearly did in your second snippet) is always fine, except it prevents undef from naturally existing in @Data.
2
my @newData = grep { !/^NULL\z/ } @Data;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.