Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to exclude elements from an array by indexes in Perl?

Tags:

arrays

perl

I use the following code to exclude elements in @{$x} at indexes in @{$index}. But I am not sure it is the most efficient way to implement this function. Does anybody have any better way to do.

sub arrayexclude {
    my $x = shift;
    my $index = shift;

    my @keep_index = (0 .. (scalar(@{$x})-1));

    delete @keep_index[@{$index}];

    my $result=[];

    for my $i (@keep_index) {
        if(defined $i) {
            push @{$result}, @{$x}[$i];
        }
    }
    return $result;
}
like image 769
user1424739 Avatar asked Oct 19 '22 13:10

user1424739


1 Answers

You don't need anything beyond an array slice, so I'd avoid creating a sub just for this.

my @wanted = @array[@indices];

If you're working with array references, the same recipe applies:

my @wanted = @{$array}[@$indices];
like image 105
Zaid Avatar answered Oct 21 '22 06:10

Zaid