As soon as you create "buckets" instead of single hashes, the algorithm also works for multiple elements per key:
my @left = qw(1 2 3 1 1); my %left; for my $l (@left) { my $key = $l; # maybe you want some more complicated key than the +item itself $left{ $key } ||= []; push @{ $left{ $key } }, $l; }; for my $r (@right) { my $key = $r; # maybe you want some more complicated key than the +item itself if (@{ $left{ $key }}) { my $found = shift @{ $left{ $key }}; print "For $key, I found the pair ($found, $r).\n"; } elsif (exists $left{ $key }) { print "For $key, there is at one item on the right side left o +ver: $r.\n"; } else { print "For $key, there is no item on the left side at all: $r. +\n"; }; }; # Now lets see if we have any values on the left side that did not pai +r: for my $l (keys %left) { my @leftover = @{ $left{ $l } }; for (@leftover) { print "For $l, there was no corresponding element on the right + side ($_)\n"; }; };
I haven't checked that code, but the approach is one I've used lots and lots when reconciling lists :)
In reply to Re^2: Searching first array in second array.
by Corion
in thread Searching first array in second array.
by paragkalra
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |