in reply to adding values of element

my $name = 'bob'; my $amount = 110; $sum{ $name } += $amount; ## sum of bob is increasing $amount = 100; $sum{ $name } += $amount; ## sum of bob is increasing $amount = 10; $sum{ $name } += $amount; ## sum of bob is increasing $amount = -100; $sum{ $name } += $amount; ## sum of bob is decreasing

Replies are listed 'Best First'.
Re^2: adding values of element
by new2perl2 (Initiate) on Jan 21, 2015 at 23:09 UTC

    Thanks for replying.

    What i want to do is read each line of the file and get the name and the amount. then read the next line and if the name exists, add the amount.

    i could write a very long winded loop to get the unique name elements then for each of them add the amount per line but i am sure there is a better way to do this.

      Just read each line, remove the line terminator (chomp) then split name and value and add value to the appropriate hash element.

      $ perl -Mstrict -Mwarnings -MData::Dumper -E ' open my $dataFH, q{<}, \ <<EOF or die $!; john, 100 barry, 300 john, 200 mary, 150 barry, 200 EOF my %names; while ( <$dataFH> ) { chomp; my( $name, $value ) = split m{\s*,\s*}; $names{ $name } += $value; } print Data::Dumper->Dumpxs( [ \ %names ], [ qw{ *names } ] );' %names = ( 'john' => 300, 'barry' => 500, 'mary' => 150 ); $

      I hope this is helpful but ask further if you need more explanation.

      Cheers,

      JohnGG

        Thanks johngg

      Hi, johngg beat me to it, but, I would have said, you could just rename %uniq to %sum and do "increasing/decreasing" inside the loop

      You got tricked by your choice of variable name, see Re^4: adding values of element, so I just wanted to emphasize that for you