in reply to How can I add the values of a hash?

Can you clarify? You mean like this?

$hash{$key} += $val1; $hast{$key} += $val2;

Replies are listed 'Best First'.
Re: Re: How can I add the values of a hash?
by Anonymous Monk on Feb 07, 2003 at 16:16 UTC
    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??? }
        Hi ,

        eval { my $values_accrued = join "+",@hash{keys %hash};print + "[$values_accrued]\n"; }


        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)

      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