Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks

How can I add the values of a hash?

i.e. my $val1; my $val2; $hash{$key} = $val1 + $val2;
how can I repeatedly do this so the value is accumulative?

Replies are listed 'Best First'.
Re: How can I add the values of a hash?
by jasonk (Parson) on Feb 07, 2003 at 15:04 UTC

    Your question could be clarified, but I'm assuming you have a hash that has numerical values, and you want to add all the values...

    my $total = 0; foreach(values %hash) { $total += $_; } print "$total\n";
Re: How can I add the values of a hash?
by steves (Curate) on Feb 07, 2003 at 14:45 UTC

    Can you clarify? You mean like this?

    $hash{$key} += $val1; $hast{$key} += $val2;
      Actually I have several unique keys, and I need to add to the value with each iteration.
      i.e. foreach (@temp) { my ($instan, $value) = (split /\*/, $_); my $k = $key . ":" . $instan; $DM_D{$k} = ($value + $value); }

        I still don't get it. That code snippet sets the hash entry at $k to two times what's in $value. It still seems to me that you're not seeing that you can use a += operator on a hash element. What am I missing?

        foreach (@temp) { my ($instan, $value) = (split /\*/, $_); my $k = $key . ":" . $instan; $DM_D{$k} += $value; # Change this line maybe??? }
        It looks to me like you want to keep a running total. If so, do something like this
        my $total=0; # running total foreach (@temp) { my ($instan, $value) = (split /\*/, $_); my $k = $key . ":" . $instan; $total += $value; # total for each iteration $DM_D{$k} = $total; }
        poj
Re: How can I add the values of a hash?
by OM_Zen (Scribe) on Feb 08, 2003 at 17:43 UTC
    Hi ,
    eval { my $values_accrued = join "+",@hash{keys %hash};print + "[$values_accrued]\n"; } #Actually the join with the "+" character with an eval on i +t accrues the values


    You can do this to accrue the values of the hash and store it to a scalar variable if that is what you need to have for the value of the addendum of the values of the hash itself .(The code is untested ,just try out and say ,I am in a friend's place with no perl in his computer ,(Hey would this work ) shall go home and test it)