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

I've got this huge array of name and time vairables
$array[0]=name<br> $array[1]=time<br> $array[2]=name<br> $array[3]=time<br>
etc...

I've got to go through and check for multiple occurances of the name, and if there is one - add the times together. I haven't been able to find an efficient way of doing this that will give me legible output. I've spent way too much time on this project... So questions are as follows:
1. Is there a way to do this efficiently?
2. Is there a way to compare two arrays to each other in this manner?
3. Would I be further off using a hash?

Anyone who has any ideas please send them on to me. I'm pretty new to Perl and am ready to beat my head on the wall over this thing...

Replies are listed 'Best First'.
Re: array problems
by Abigail-II (Bishop) on Aug 14, 2002 at 16:46 UTC
    my %data; while (@array) { my ($name, $time) = splice @array => 0, 2; $data {$name} += $time; }
    This should answer points 1 and 3. As for 2, I do not know what you want to compare.

    Abigail

Re: array problems
by thelenm (Vicar) on Aug 14, 2002 at 16:49 UTC
    You can create a hash with the total time for each name by doing something like this:
    for (my $i=0; $i<@array; $i+=2) { my ($name, $time) = @array[$i,$i+1]; $hash{$name} += $time; }

    -- Mike

    --
    just,my${.02}

Re: array problems
by Zaxo (Archbishop) on Aug 14, 2002 at 17:00 UTC

    Build a hash keyed on the names, and add the times

    my %hash; my ($name,$time); while (@array) { $time = pop @array; $name = pop @array; $hash{$name} += $time; }
    The while (@array) condition remains true as long as @array is not empty. I use pop so that @array doesn't move. You may need to adapt if your time elements are formatted to exclude simple arithmetic.

    After Compline,
    Zaxo

Re: array problems
by Aristotle (Chancellor) on Aug 14, 2002 at 21:33 UTC
    my %time_for; { my ($name,$time); $time_for{$name} += $time while ($name,$time) = splice @array, 0, +2; }
    ____________
    Makeshifts last the longest.