On Mon, 2 Jul 2001, Perl Beginner wrote:
> I'm your typical beginner who is kind of stuck. Here is the problem:
>
> I have two hashes, each has ~40,000 key/value pairs. I need to find which
> keys in one hash are the same as the keys in the other hash. The ones that
> have the same key then need their values diffed. This is how I was trying to
> accomplish this:
>
> while (($key1,$value1) = each (%yesterdayhash)) {
> while (($key2,$value2) = each (%todayhash)) {
>
> if (($key1 eq $key2) {
> $delta = ($value2 - $value1) ;
> }
> }
> }
>
> I let this run for over 48 hours and it never completed! One of our Perl
> experts said I did a big no-no. Everything in those while statements will be
> iterating ~40,000 * 40,000 times.
Yep, you only need one loop. Here's the answer fron the Perl Cookbook:
my @common = ();
foreach (keys %hash1) {
push(@common, $_) if exists %hash2{$_};
}
Then you can do what you need with the elements of @common to find the
values in the two hashes.
-- Brett
http://www.chapelperilous.net/btfwk/
------------------------------------------------------------------------
If you don't have time to do it right, where are you going to find the time
to do it over?