in reply to Silly array-ish question.

Whenever I see a "sum this if that matches" type problem, I always think hash.

Given your 2-d array above, how about:

my %sums; for( my $i = 0; $i < $lines; ++$i ) { $sums{$data[$i][1]} += $data[$i][3]; }

The %sums hash now contains the sums keyed by the day (if I'm understanding what field 1 is).

Personally, I would tend to write this much more compactly, but this should work and is easier to understand.

Update: fixed stupid typoes. (Thanks JadeNB).

G. Wade

Replies are listed 'Best First'.
Re^2: Silly array-ish question.
by gone2015 (Deacon) on Oct 23, 2008 at 16:53 UTC

    Indeed. Though you are into some form of date processing if:

    • you cannot depend on every instance of the date for a given day being in exactly the same form.
    • you want to extract the sum for any given day.
    • you want to spit out the sums in any particular order.
Re^2: Silly array-ish question.
by gwadej (Chaplain) on Oct 23, 2008 at 18:28 UTC

    You're right. For a complete solution, I'd probably have done more. At the very least, I should have shown some code to walk the hash in some reasonable order to print the results.

    foreach my $date (sort by_date keys %sums) { print "$sums{$date}\n"; }

    where by_date is a subroutine that can compare the two dates in $a and $b appropriately for sort.

    For a more robust solution, you could also take the date values and convert them into some canonical form before using them as keys in the hash. (If that's easier to sort, so much the better.)

    To start with, though, I really didn't want to generate a response that was too complicated to understand in the simple case.
    G. Wade