Akens, Anthony wrote:
Hi,
I'm new to hashes, and I've been playing around with the following for a while... I'm just not getting it.


I have two hashes, one containing data read in from a file, one with "current" data. I'd like to merge the two, adding any new keys and values into the hash, and for any keys that exist in both, I'd like the append the values onto the values for the same key in the original hash.

An example...

Hash 1 (from a file)

host1=>"760,760,759"
host2=>"765,760,760"
host5=>"130,200"

Hash 2 (Current)

host1=>"758"
host2=>"760"
host4=>"450"
host5=>"210"

I'd like the merged hash to be:

host1=>"760,760,759,758"
host2=>"765,760,760,760"
host5=>"130,200,210"
host5=>"450"

Instead of string values in the main hash, you might want to use arrays or more hashes. Pardon my syntax as I've never done something like this before:


my $hash1 = { host1 => (760, 760, 759),
              host2 => (765, 760, 760),
              host5 => (130, 200) };

my $hash2 = { host1 => (758),
              host2 => (760),
              host4 => (450),
              host5 => (210) };

I'm using an example out of the perl cookbook, and trying to
modify it to do what I want, but it isn't working out...

The three hashes are: %host_list (Hash 1 in the example)
%current_list (Hash 2 in the example)
%final_list (The result of the merge)


Here's the code I have so far for the merge (this is borrowed
heavily from the Perl Cookbook):

foreach $item ( \%host_list, \%current_list) {
    while (($key, $value) = each %$item) {
        if (exists $final_list{$key}) {
            $value .= ",$current_list{$key}";
        }
        $final_list{$key} = $value;
        
    }
}
>
Can someone point me in the right direction?

I tried to come up with some code to combine the hashes, but I'm having a brain fart. Even without code to back it up, I still recommend the arrays or hashes within the hash approach instead of strings within the hash.


--
Andrew Gaffney
Network Administrator
Skyline Aeronautics, LLC.
636-357-1548


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to