在Perl中通过索引从数组中排除元素的最佳方法是什么? [英] What is the best way to exclude elements from an array by indexes in Perl?

查看:104
本文介绍了在Perl中通过索引从数组中排除元素的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码在 @ {$ index} @ {$ x} 中的元素>。但是我不确定这是实现此功能的最有效方法。有人有更好的方法吗?

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


推荐答案

您不需要任何东西除了数组切片之外,因此我避免为此创建一个子项。

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];

这篇关于在Perl中通过索引从数组中排除元素的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆