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; } } #### my (%db_lookup, %in_lookup); @db_lookup{@db} = (); @in_lookup{@in} = (); if ($condition1) { # Dunno what your test conditions are, so... @db = grep { not exists $in_lookup{$_} } @db; } elsif ($condition2) { push @db, grep { not exists $db_lookup{$_} } @in; }