Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: 2d Array - making an array for the column then adding the values

by Sandy (Curate)
on Sep 21, 2009 at 02:33 UTC ( #796472=note: print w/ replies, xml ) Need Help??


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; }


Comment on Re: 2d Array - making an array for the column then adding the values
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://796472]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2014-12-26 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (164 votes), past polls