From: Andrew Gaffney <[EMAIL PROTECTED]>
> Akens, Anthony wrote:
> > 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.
>
> 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) };
I completely agree with the idea. The syntax is a little off though.
It should be:
my $hash1 = { host1 => [760, 760, 759],
host2 => [765, 760, 760],
host5 => [130, 200] };
Notice the square brackets. Your code would be equivalent to
my $hash1 = { host1 => 760,
760 => 759,
host2 => 765,
760 => 760,
host5 => 130,
200 => undef};
> my $hash2 = { host1 => (758),
> host2 => (760),
> host4 => (450),
> host5 => (210) };
This is exactly the same as
my $hash2 = { host1 => 758,
host2 => 760,
host4 => 450,
host5 => 210 };
The code depends on whether you use a one-element array or the value
directly if there is just one value for the key:
%hash1 = (
host1 => [760, 760, 759],
host3 => [752],
); # no need to use a hash ref
vs.
%hash1 = (
host1 => [760, 760, 759],
host3 => 752,
); # no need to use a hash ref
And whether there can be several values in the second hash.
Assuming that you use the one-element arrays and the second array
always contains just one value you could write it like this:
foreach my $key (keys %hash2) {
push @{$hash1{$key}}, $hash2{$key};
}
or
while (my ($key, $value) = each $hash2) {
push @{$hash1{$key}}, $value;
}
if you stored single values directly you'd have to split the logic
into three branches:
while (my ($key, $value) = each $hash2) {
if (exists $hash1{$key}) {
if (ref $hash1{$key}) {
# 1) already an array
push @{$hash1{$key}}, $value;
} else {
# 2) a single value
$hash1{$key} = [$hash1{$key}, $value]
}
} else {
# 3) no value yet
$hash1{$key} = $value;
}
}
HTH, Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>