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

Hi, I'm struggling with the following part of a program that I am writing. I currently have 3 arrays.
Array 1 contains names e.g. (jim, steve, jim2, terry, steve)
Some of these names are repeated numerous times
Array 2 contains numbers e.g. (1, 3, 5, 2, 4)
Array 1 and Array 2 are the same size.

Now what I am trying to do is look through the names and then add up the corresponding number, and then print the output. Thus, in the above example my final output should look like:

jim 1 steve 7 jim2 5 terry 2
I have set-up a third array which reads array 1 and just takes the unique names. Then I thought that a 4th array could be built by going through array3, looking for a match in array1, and adding the corresponding number. The final number being pushed into array4, so that at the end I just need to print array3 and array4.

But nothing I do seems to work, and now I have so many # lines in my program trying different things that I'm lost in the confustion.

Edit by tye

Replies are listed 'Best First'.
Re: multiple arrays and lists
by DamnDirtyApe (Curate) on Jul 31, 2002 at 04:13 UTC
    #! /usr/bin/perl use strict ; use warnings ; use Data::Dumper ; $|++ ; my @arr1 = qw/ jim steve jim2 terry steve / ; my @arr2 = qw/ 1 3 5 2 4 / ; my %hash = () ; for ( 0 .. $#arr1 ) { $hash{$arr1[$_]} += $arr2[$_] } print Dumper( \%hash ) ; exit ; __END__

    _______________
    D a m n D i r t y A p e
    Home Node | Email
Re: multiple arrays and lists
by Bilbo (Pilgrim) on Jul 31, 2002 at 10:25 UTC
    As DamnDirtyApe says, you probably want to use a hash instead of arrays 3 and 4. A hash lets you associate a value with a 'key', so if we have a hash called %hash we can set $hash{steve} = 2 for example. You should set up the hash then loop over the arrays. For each entry in the arrays use the name as the key to the hash and add the value in array2 to this entry in the hash. My program doesn't really add much to DamnDirtyApe's except that using Data::Dumper to print a small hash seems like overkill.
    # The two arrays are in @arr1 and @arr2 my %hash; # loop over the arrays for (0..$#arr1) { # Add the value from arr2 to the approprate entry in # the hash $hash{$arr1[$_]} += $arr2[$_]; } foreach (keys(%hash)) { print "$_ $hash{$_}\n"; }