my %lookup; @lookup{@in} = (); # For every $elem in @db ... foreach my $elem (@db) { # see if it exists in the lookup hash ... if (exists $lookup{$elem}) { # and if it does then search @db (*again*) looking for # items that do not appear in the lookup hash. You're # also modifying the array you're iterating over (@db), # which can yield unpredictable results, so don't do it ;) @db = grep {not exists $lookup{$_}} @db; } }