Perl-合并包含重复键的哈希 [英] Perl - Merge hash containing duplicate keys

查看:489
本文介绍了Perl-合并包含重复键的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个可以包含相同密钥的哈希.我正在尝试以一种方式合并两个哈希,如果密钥存在于两个哈希中,我想将值添加到各个哈希中.

I have two hashes which can contain the same keys. I am trying to merge the two hashes in such a way that if the key exists in both the hashes, I want to add the values in the respective hashes.

my %hash1= ();
$hash1{'apple'} = 10;
$hash1{'banana'} = 15;
$hash1{'kiwi'} = 20;

my %sourceHash = ();
$sourceHash{'apple'} = 12;
$sourceHash{'orange'} = 13;
$sourceHash{'banana'} = 5;


mergeHash(\%hash1, \%sourceHash);


sub mergeHash {
    my $hash1 = shift;
    my $hash2 = shift;

    foreach my $key (keys %{$hash1})
    {
        if (exists $hash2->{$key}) {
            ${hash2}->{$key} = $hash1->{$key} + $hash2->{$key};
        } else {
            ${hash2}->{$key} = $hash1->{$key};
        }
    }
}

我希望hash1的结果是

I expect the result of hash1 to be

hash1{'apple'} = 22;
hash1{'orange'} = 13;
hash1{'banana'} = 20;
hash1{'kiwi'} = 20;

但是我得到一个异常,说不能在标量分配中修改常量项目.我在做什么错了?

But I get an exception saying Can't modify constant item in scalar assignment. What am I doing wrong?

推荐答案

PFB使用正确的语法更新了代码,并且还提供了所需的输出:

PFB the updated code with proper syntax and it is giving the desired output also:

my %hash1= ();
$hash1{'apple'} = 10;
$hash1{'banana'} = 15;
$hash1{'kiwi'} = 20;

my %sourceHash = ();
$sourceHash{'apple'} = 12;
$sourceHash{'orange'} = 13;
$sourceHash{'banana'} = 5;

mergeHash(\%hash1, \%sourceHash);


sub mergeHash {
    my $param1 = shift;
    my %hash1 = %$param1;
    my $param2 = shift;
    my %hash2 = %$param2;

    foreach my $key (keys %hash1){
        if(exists $hash2{$key}){
            print "coming in here for $hash1->{$key} \n";
            $hash2{$key} = $hash1{$key} + $hash2{$key};
        }
        else{
            $hash2{$key} = $hash1{$key};
        }
    }
    showHash(\%hash2);
}
sub showHash{

    my $param = shift;
    my %param_hash = %$param;


    for my $fruit (keys %param_hash) {
    print "The value of '$fruit' is $param_hash{$fruit}\n";
    }
}

这篇关于Perl-合并包含重复键的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆