FAQ
Hi Gurus!

This may be a simple question but so far I cannot find an
answer. How can I combine hashs so that if both hashs have
the same key but with different values, the values from
both will get merged. I'm currently using:

%hash1 = (%hash1, %hash2);

Each time I lose the larger value.

Thanks!

-Mark

Search Discussions

  • Andrea Holstein at Oct 22, 2001 at 7:33 am

    Hanson wrote:

    This may be a simple question but so far I cannot find an
    answer. How can I combine hashs so that if both hashs have
    the same key but with different values, the values from
    both will get merged. I'm currently using:

    %hash1 = (%hash1, %hash2);
    What do you mean with merging the values.
    For every key, there will be only one value in the result.

    E.g. if you want to calculate the average of the values,
    the following snippet will do:

    my %merged_hash = %hash1;
    while (my ($key, $val) = each %hash2) {
    defined $merged_hash{$key} ?
    $merged_hash{$key} = ($val + $merged_hash{$key}) / 2 :
    $merged_hash{$key} = $val;
    }

    Greetings,
    Andrea

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupbeginners @
categoriesperl
postedOct 22, '01 at 1:26a
activeOct 22, '01 at 7:33a
posts2
users2
websiteperl.org

2 users in discussion

HANSON: 1 post Andrea Holstein: 1 post

People

Translate

site design / logo © 2022 Grokbase