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

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); }

Replies are listed 'Best First'.
Re: Re: Re: How can I add the values of a hash?
by steves (Curate) on Feb 07, 2003 at 17:24 UTC

    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)

Re: Re: Re: How can I add the values of a hash?
by poj (Abbot) on Feb 08, 2003 at 18:52 UTC
    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