in reply to Combining hashes

My thought regarding merging hashes would be to make the values into references to anonymous arrays. The following demonstrates a roughly hacked "merge" subroutine that takes references to hashes, grabs all unique keys, and then iterates over the keys to build an array containing values in all hashes. I'm sure someone else can come behind me to improve this :)

Incidentally, what I like about this solution is that you don't lose any data!

use strict; use warnings; use Data::Dumper; my %first = ( one => 1, two => 2, three => 3 ); my %second = ( one => 'uno', two => 'dos', foo => 'bar' ); my %third = ( one => [ 'this', 'is', 'a', 'test' ], two => 'dos', foo => { bar => 'raise', baz => 'test' } ); my %new_hash = merge( \%first, \%second, \%third ); print Dumper( \%new_hash ); sub merge { my @hashes = @_; my ( %merged_hash, %temp, @keys ); # grab unique keys foreach my $hash ( @hashes ) { foreach my $key ( keys %$hash ) { push @keys, $key if ! $temp{ $key }++; } } my @vals; # build the array foreach my $key ( @keys ) { foreach my $hash ( @hashes ) { push @vals, $hash->{ $key } if exists $hash->{ $key }; } $merged_hash{ $key } = [@vals]; @vals = (); } return %merged_hash; }
Output:
$VAR1 = { 'one' => [ 1, 'uno', [ 'this', 'is', 'a', 'test' ] ], 'three' => [ 3 ], 'foo' => [ 'bar', { 'baz' => 'test', 'bar' => 'raise' } ], 'two' => [ 2, 'dos', 'dos' ] };
Note that it even allows you to merge complex data structures. Of course, I haven't tested (or commented) this too thoroughly, so there is no warranty included.

This answers your question about merging hashes. Of course, to get the country count, simply merge the hashes and and count the keys.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid - use a HoA to merge hashes) Re: Combining hashes
by MeowChow (Vicar) on May 11, 2001 at 22:32 UTC
    sub merge { my %merged; for (@_) { while (my ($k, $v) = each %$_) { push @{$merged{$k}}, $v; } } %merged; }
    Though, if I were using this, I would prefer for it to a return a reference.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print