Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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 ( [id://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; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-29 12:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found