in reply to hashes with multiple values per key

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

Replies are listed 'Best First'.
Re^2: hashes with multiple values per key
by convenientstore (Pilgrim) on Aug 07, 2007 at 00:30 UTC
    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.

        not quite. Consider:

        use strict; use warnings; my $foo = undef; my $bar = undef; $foo += 1; $bar = $bar + 1;

        Generates the warning:

        Use of uninitialized value in addition (+) at noname1.pl line 8.

        Note that it is the $bar line only that generates the warning. The update assignment operators do not generate an uninitialized value warning when the left hand side is undefined, but the other non-boolean binary operators do. See perlsyn Declarations.


        DWIM is Perl's answer to Gödel