http://www.perlmonks.org?node_id=796472


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

Hello,

Please, next time, try to post only the code that exposes your problem.

The problem that you directed us to is in the following

sub score_count { my @arr = shift; my $total = 0; foreach my $score (@arr) { print "@$score "; $total += @$score; } print "$total\n"; return $total; }
Although there are other issues, lets look at this code. @arr is being fed a single element (via the shift command).

This makes @arr an array of an array

Your code print @$score I believe misled you to believe that use @$score will give you all the values one at a time. It does only because print processes an array in list mode.

In the next line, the code $total += @$score; processes the array in SCALAR context, which will return the TOTAL number of elements in your array (which is 60), NOT the sum of each value.

What you need is:

foreach my $score (@arr) { foreach my $i (@$score) { $total += $i; } }
Or, better yet (notice $arr instead of @arr):
sub score_count { my $arr = shift; my $total = 0; foreach my $score (@$arr) { $total+= $score; } print "total: $total\n"; return $total; }