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.

1
  • 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...
    – User0
    Jul 17, 2014 at 20:25
2

Combining @toolic and @user2752322:

delete @Data[@cuts];
my @newData = grep { defined } @Data;
3
  • undef @Data[@cuts] or @Data[@cuts] = () would be preferable to delete.
    – Slade
    Jul 17, 2014 at 19:26
  • @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
    Jul 17, 2014 at 20:00
  • @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.
    – ikegami
    Jul 18, 2014 at 4:08
2
my @newData = grep { !/^NULL\z/ } @Data;
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.