问题 - 我有两个数组,如下所示。
my @arr1 = qw( jon won don pon );
my @arr2 = qw( son kon bon won kon don pon won pon don won);
我需要从@arr2 中删除@arr1 的第一个匹配元素,即在上面的示例中,我需要从@arr2 中删除won。
目前我的逻辑如下。
#!/usr/bin/perl
my @arr1 = qw( jon won don pon );
my @arr2 = qw( son kon bon won kon don pon won pon don won);
my @remove_indices = ();
my $remove_element;
my $first_remove_index;
OUTER_FOR: for my $i (0..@arr2) {
$outer_element = $arr2[$i];
foreach my $innr_element ( @arr1 ) {
if($innr_element eq $outer_element) {
push(@remove_indices, $i);
$first_remove_index = $i;
$remove_element = $innr_element;
last OUTER_FOR;
}
}
}
for my $i ($first_remove_index+1..@arr2) {
$outer_element = $arr2[$i];
if($remove_element eq $outer_element) {
push(@remove_indices, $i);
}
}
if (@remove_indices > 0) {
map {splice (@arr2, $_, 1)} reverse(@remove_indices);
}
print "@arr2";
但这似乎是典型的 C/C++ 风格逻辑。我不能使用哈希。有没有 perl 方法可以做到这一点?