在执行脚本时,我需要删除数组的多个元素(这些元素不是顺序的).我将在执行脚本时获取我的数组和索引.
例如:
我可能会得到一个数组和索引列表,如下所示:
my @array = qw(one two three four five six seven eight nine);
my @indexes = ( 2, 5, 7 );
Run Code Online (Sandbox Code Playgroud)
我有以下子程序来做到这一点:
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;
}
Run Code Online (Sandbox Code Playgroud)
如果我调用我的子程序如下:
splicen(\@array , @indexes);
Run Code Online (Sandbox Code Playgroud)
这对我有用,但是:
有没有更好的方法来做到这一点?
相反,如果您从数组的末尾拼接,则不必维护偏移量$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;
}
}
Run Code Online (Sandbox Code Playgroud)