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

I have file below
12 AAAA 12 AAAA 15 BBBB 1222 CCCC 1 BBBB
and I am trying to run below so that I can gather everything
so that it would show

AAAA 24
BBBB 16
CCCC 1222
But below codes just do not add them together..
use strict; my $value; my $key; my $sum = 0; my %yahoo = (); while (<>) { ($value,$key) = split; # print "$key, $value\n"; # $sum += $value; # print "\$sum is $sum\n"; push (@{$yahoo{$key}}, ($sum += $value)); } foreach $key (sort keys %yahoo) { print "$key: @{$yahoo{$key}}\n"; }

Replies are listed 'Best First'.
Re: hashes with multiple values per key
by kyle (Abbot) on Aug 06, 2007 at 22:54 UTC
    use strict; use warnings; my %yahoo = (); while (<DATA>) { chomp; my ($value, $key) = split; $yahoo{$key} += $value; } foreach my $key (sort keys %yahoo) { print "$key: $yahoo{$key}\n"; } __DATA__ 12 AAAA 12 AAAA 15 BBBB 1222 CCCC 1 BBBB

    Output:

    AAAA: 24 BBBB: 16 CCCC: 1222
      I didn't think below would work but it works
      $yahoo{$key} += $value;
      isn't above same as
      $yahoo{$key} = $yahoo{$key} + $value
      so first $yahoo{$key} would be null + $value and then next time it would come up with that value so that's why it works
      great!! thank you. Grandfather's solution , is bit advance for me, as I have not got to module part but I am reading that tonight and will try. thank you both !!!

        Yes, "$yahoo{$key} += $value;" is the same as "$yahoo{$key} = $yahoo{$key} + $value;". Look under "Assignment operators" in perlop.

Re: hashes with multiple values per key
by GrandFather (Saint) on Aug 06, 2007 at 23:03 UTC

    You could sum as you go, or you could sum afterwards:

    use strict; use warnings; use List::Util; my %yahoo = (); while (<DATA>) { my ($value,$key) = split; push @{$yahoo{$key}}, $value; } foreach my $key (sort keys %yahoo) { my $sum = List::Util::sum (@{$yahoo{$key}}); print "$key: $sum\n"; } __DATA__ 12 AAAA 12 AAAA 15 BBBB 1222 CCCC 1 BBBB

    Prints:

    AAAA: 24 BBBB: 16 CCCC: 1222

    DWIM is Perl's answer to Gödel