in reply to array of arrays

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

Replies are listed 'Best First'.
Re^2: array of arrays
by Anonymous Monk on Jun 12, 2017 at 01:23 UTC

    Hello Marshall:

    I like your solution.. it does way with indices as you say. I copied it to my file and works great.

    Now how would you do the same thing if the test_file.txt would be like this..??

    1|10
    1|20
    1|30
    1|40
    1|50
    2|15
    2|25
    2|35
    3|1
    3|2
    3|3
    3|4
    3|5
    3|6
    3|7
    3|8
    3|9
    3|10

      kevbot and Marshall have already given solutions that handle the  1|10 organization of data. What was wrong with these approaches? If you can identify and clearly explain shortcomings, I'm sure they can be addressed.


      Give a man a fish:  <%-{-{-{-<