sundeep has asked for the wisdom of the Perl Monks concerning the following question:

I used the following code to check the hash keys in 2 hashes and print the same occurring hash key and its respective value

while (((my $key1,my $value1)=each(%websites))) { while (((my $key2,my $value2)=each(%newsites))) { if($key1 = $key2) { print "$key2=$value2 \n"; } } }

But, i want to sort the hash keys numerically in both the hash tables and then print the common key and the value . So how can i sort and print it simultaneously

Replies are listed 'Best First'.
Re: Sort and Print Hashes simultaneously
by moritz (Cardinal) on Nov 01, 2010 at 16:42 UTC
    Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi. -- TimToady
    for my $key (sort { $a <=> $b } keys %websites) { if (exists $newsites{$key}) { print "$key=$newsites{$key}\n"; } }

    See also: sort, keys, exists, perlfaq4.

    Perl 6 - links to (nearly) everything that is Perl 6.
      Thanks a lot... I really don't know that, i can do it without a linear search. Anyways, i am learning a lot from u guys.... thanks for the immediate reply....
Re: Sort and Print Hashes simultaneously
by kennethk (Abbot) on Nov 01, 2010 at 16:47 UTC
    First, $key1 = $key2 is an assignment, not a logical test (==) -- see perlop. This will return true provided the value in $key2 evaluates to true. warnings would have issued a warning if you'd tested your code before posting. See How do I post a question effectively?.

    You need only loop over one hash - you can easily test if that key is present in the second hash by accessing it as a hash. You can sort the keys in the loop declaration.

    for my $key (sort { $a <=> $b } keys %websites) { if (exists $newsites{$key1}) { print "$key=$newsites{$key1}\n"; } }

    Most of this is discussed in the Data: Hashes (Associative Arrays) section of perlfaq4.