I re-looked at your original code and my brain hurts!

It is of course possible to use indices to access a 2-D array in Perl, however this is not the normal situation. A far, far more normal situation is to access each row as an array of values. This is also true in C albeit with different syntax than this.

I re-wrote your code below.
These integer index buddies of i and j just don't appear that often in Perl code. Of course Perl allows that syntax. Note that by "not often", I do not mean "never". The most common errors in programming are memory allocation errors and "off by one" errors when using array indices or when looping. Perl for the most part takes care of memory allocation for you in a very efficient way - you don't have to worry about it unless you are doing something really fancy. This "off by one error" stuff can be much more problematic. In general don't use i or j indices unless you have to.

#!/usr/bin/perl use strict; use warnings; my @AoA; while (my $line = <DATA>) { my @tmp = split ' ',$line; push @AoA, [ @tmp ]; } ## Print the totals for each line ### ## and the final grand_total ### my $grand_total; foreach my $row_ref (@AoA) { my $line_total; foreach my $num (@$row_ref) { $line_total += $num; } print "Line Total: $line_total\n"; $grand_total += $line_total; } print "Grand Total: $grand_total\n"; =Prints: Line Total: 150 Line Total: 75 Line Total: 55 Grand Total: 280 =cut __DATA__ 10 20 30 40 50 15 25 35 1 2 3 4 5 6 7 8 9 10

In reply to Re: array of arrays by Marshall
in thread array of arrays by virtualweb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.