我有2个数组。一个将包含我要删除的内容,另一个将是主数组。
所以可以说
my @main_array = ("apple","bob","cat","dog","earth");
my @stuff_to_delete_array = ("bob","dog");
我希望最终的main_array具有("apple","cat","earth")
。可以说我不知道索引。是否可以在main_array中搜索"bob"
和"dog"
并将其删除?
答案 0 :(得分:4)
my @items = ( "apple", "bob", "cat", "dog", "earth" );
my @to_delete = ( "bob", "dog" );
# Create a hash for quick lookup
my %to_delete = map { $_ => 1 } @to_delete;
my @filtered = grep { !$to_delete{$_} } @items;
此解决方案保留了@items
中项目的顺序。
答案 1 :(得分:3)
您可以使用模块Array::Utils
。该模块支持删除可以比较两个数组元素的元素。
#!/usr/bin/perl
use 5.010;
use Array::Utils qw(:all);
my %cmp = ();
my @main_array = ("apple","bob","cat","dog","earth");
my @stuff_to_delete_array = ("bob","dog");
my @output = array_minus(@main_array, @stuff_to_delete_array);
print join "\n", @output;
您可以尝试一下。
答案 2 :(得分:1)
将数组转换为哈希在这里可能会很方便:
my %h;
@h{ @main_array } = ();
delete @h{ @stuff_to_delete_array };
@main_array = keys %h;