正如 ysth 已经指出的那样,在直接迭代其元素时尝试修改数组是不明智的。
但是,如果确实想根据元素值修改数组,诀窍是按反向索引顺序进行。
例如,假设我有一个数字数组。我想修改数组,以便每个 4 的倍数在其后插入一个字符串,并删除每个 5 的倍数。我会使用以下方法来完成:
use strict;
use warnings;
my @array = ( 1 .. 20 );
for my $i ( reverse 0 .. $#array ) {
# Insert after multiples of 4
if ( ( $array[$i] % 4 ) == 0 ) {
splice @array, $i + 1, 0, "insert";
}
# Remove multiples of 5
if ( ( $array[$i] % 5 ) == 0 ) {
splice @array, $i, 1;
}
}
use Data::Dump;
dd @array;
输出:
(
1 .. 4,
"insert",
6,
7,
8,
"insert",
9,
11,
12,
"insert",
13,
14,
16,
"insert",
17,
18,
19,
"insert",
)
或者,如果你想转换一个数组,也可以像这样使用map:
my @newarray = map {
( ( ($_) x !!( $_ % 5 ) ), # Remove multiples of 5
( ('insert') x !( $_ % 4 ) ), # Insert After multiples of 4
)
} ( 1 .. 20 );
use Data::Dump;
dd @newarray;