in reply to Re: adding values of element
in thread adding values of element

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.

Replies are listed 'Best First'.
Re^3: adding values of element
by johngg (Canon) on Jan 21, 2015 at 23:58 UTC

    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
Re^3: adding values of element
by Anonymous Monk on Jan 22, 2015 at 00:42 UTC

    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