in reply to How can you make this script general?

If all you need to do is calculate the sums then this might help:
my %count; while (my $line = <DATA>) { chomp $line; my @cols = split("\t",$line); $count{$_} += $cols[$_] for 0 .. $#cols; } for my $col_num (sort { $a <=> $b } keys %count) { print "Total for column $col_num: $count{$col_num}\n"; } __DATA__ 1 2 3 4 3 4 5 6 6 7 8 9
Output:
Total for column 0: 10 Total for column 1: 13 Total for column 2: 16 Total for column 3: 19

Replies are listed 'Best First'.
Re^2: How can you make this script general?
by BrowserUk (Patriarch) on Mar 08, 2014 at 20:33 UTC

    Why use a hash and then have to sort, when the column numbers are ... well, numbers?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Why use a hash and then have to sort
      Just a habit really. An array would be more efficient.
      perhaps tangent wants to be prepared for the general case, where the columns have names...
        to be prepared for the general case, where the columns have names...

        Still makes no sense to waste cycles sorting hash keys:

        #! perl -slw use strict; my @colnames = split ' ', <DATA>; my @totals; while( <DATA> ) { my @cols = split; $totals[ $_ ] += $cols[ $_ ] for 0 .. $#cols; } printf "%10s:%u\n", $colnames[$_], $totals[$_] for 0 .. $#totals; __DATA__ alpha beta gamma delta 1 2 3 4 5 6 7 8 9 10 11 12

        Produces:

        C:\test>junk alpha:15 beta:18 gamma:21 delta:24

        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
        i