删除Perl数组中的多个非顺序元素的“最佳”方法是什么?

时间:2014-08-15 08:52:13

标签: arrays perl

执行脚本时,我需要删除数组的多个元素(这些元素不是顺序的)。我将在执行脚本时获取我的数组和索引。

例如:

我可能会得到一个数组和索引列表,如下所示:

my @array = qw(one two three four five six seven eight nine);

my @indexes = ( 2, 5, 7 );

我有以下子程序来执行此操作:

sub splicen {
    my $count     = 0;
    my $array_ref = shift @_;

    croak "Not an ARRAY ref $array_ref in $0 \n"
        if ref $array_ref ne 'ARRAY';

    for (@_) {
        my $index = $_ - $count;
        splice @{$array_ref}, $index, 1;
        $count++;
    }

    return $array_ref;
}

如果我调用我的子程序如下:

splicen(\@array , @indexes);

这对我有用,但是:

有没有更好的方法呢?

2 个答案:

答案 0 :(得分:7)

如果您从数组的末尾拼接而来,则不必保持偏移量$count

sub delete_elements {
    my ( $array_ref, @indices ) = @_;

    # Remove indexes from end of the array first
    for ( sort { $b <=> $a } @indices ) {
        splice @$array_ref, $_, 1;
    }
}

答案 1 :(得分:1)

另一种思考方式是构建一个新数组而不是修改原始数组:

my @array   = qw(one two three four five size seven eight nine);
my @indexes = (2, 5, 7);
my %indexes = map { $_ => 1 } @indexes;
my @kept    = map { $array[$_] } grep { ! exists $indexes{$_} } 0 .. $#array;