in reply to 2d Array - making an array for the column then adding the values

sigh...
Its all good - we've all been here and done something silly at some point or other :)

What your score_count sub is doing is summing the element counts of the arrays rather than the contents of them...

Try this:
sub score_count { my @arr = shift; my $total = 0; foreach my $score (@arr) { print "@$score "; foreach my $i (@$score){ $total += $i; } } print "$total\n"; return $total; }
  • Comment on Re: 2d Array - making an array for the column then adding the values
  • Download Code

Replies are listed 'Best First'.
Re^2: 2d Array - making an array for the column then adding the values
by ikegami (Patriarch) on Sep 21, 2009 at 02:31 UTC

    Good catch. What follows is a more detailed explanation.

    The original code

    $total += @$score;

    adds an array to $total. What's the value of an array? Well, arrays don't naturally have a value. It turns out it's very convenient for arrays to return the number of elements it contains as its value. It allows us to replace calls to (non-existent) function array_length(@array) with just @array, a very common operation.

    If you want to sum the values of the array's elements, you'll have to sum the values of the array's elements. I showed two ways of doing that in my earlier post.

Re^2: 2d Array - making an array for the column then adding the values
by hansoffate (Novice) on Sep 21, 2009 at 02:37 UTC
    Thanks for your great explanation and code! This fixed the problem.
      Glad I could help ;)