in reply to array of arrays

Your existing code will work with very little change.
while (<TESTFILE>) { #@tmp = split; # Split elements into an array. #push @AoA, [ @tmp ]; # Add an anonymous array reference +to @AoA. @tmp = split /\|/; $AoA[$tmp[0]-1] = []if !defined $AoA[$tmp[0]-1]; push @{$AoA[$tmp[0]-1]}, $tmp[1]; }
Bill

Replies are listed 'Best First'.
Re^2: array of arrays
by Anonymous Monk on Jun 11, 2017 at 16:22 UTC

    Hi Bill:
    Thanx for your suggestion.. I like your solution very much because it only adds a few lines to the existing example instead of re-building the whole thing. How would print the totals..??

      Modifying existing software to support new requirements is called "Maintenance". (A poor choice of words, but were stuck with it.) Few of us ever get the luxury to start over, even when it would be cheaper in the long term. In the short term, it is almost always faster to cram in one more change. In that spirit, I suggest:
      my $Grand_Total = 0; for $i ( 0 .. $#AoA ) { $row = $AoA[$i]; for $j ( 0 .. $#{$row} ) { $Total_Balance[$i] += "$row->[$j]"; } print "the total is: ($Total_Balance[$i])<hr>\n"; $Grand_Total += $Total_Balance[$i]; } print "Grand Total is: ($Grand_Total)<hr>\n" _

      But wouldn't you prefer to write:

      use strict; use warnings; use List::Util qw(sum); my @AoA; while (<DATA>) { my ($index, $value) = split /\|/; push @{ $AoA[$index-1] }, $value; } my @Total_Balance = map {sum( @$_ )} @AoA; print "The total is: ($_)\n" foreach @Total_Balance; print "Grand total is: (", sum( @Total_Balance ), ")\n"; __DATA__ 1|10 1|20 1|30 1|40 1|50 2|15 2|25 2|35 3|1 3|2 3|3 3|4

      This design is neither fast nor small. Its merit is that each pass through the data can only do one thing. You can understand, validate, or modify any section without concern about side effects.

      Bill