ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
4.7. Finding Elements in One Array but Not AnotherProblemYou want to find elements that are in one array but not another. SolutionYou want to find elements in Straightforward implementation# assume @A and @B are already loaded %seen = (); # lookup table to test membership of B @aonly = (); # answer # build lookup table foreach $item (@B) { $seen{$item} = 1 } # find only elements in @A and not in @B foreach $item (@A) { unless ($seen{$item}) { # it's not in %seen, so add to @aonly push(@aonly, $item); } } More idiomatic versionmy %seen; # lookup table my @aonly;# answer # build lookup table @seen{@B} = (); foreach $item (@A) { push(@aonly, $item) unless exists $seen{$item}; } DiscussionAs with nearly any problem in Perl that asks whether a scalar is in one list or another, this one uses a hash. First, process The given code retains duplicate elements in foreach $item (@A) { push(@aonly, $item) unless $seen{$item}; $seen{$item} = 1; # mark as seen } The two solutions differ mainly in how they build the hash. The first iterates through $hash{"key1"} = 1; $hash{"key2"} = 2; is equivalent to: @hash{"key1", "key2"} = (1,2); The list in the curly braces holds the keys; the list on the right holds the values. We initialize @seen{@B} = (); This uses items in @seen{@B} = (1) x @B; See AlsoHash slices are explained in perldata (1) and the "Variables" section of Chapter 2 of Programming Perl; Chapter 5; we use hashes in a similar fashion in Recipe 4.6 and Recipe 4.8 |