If you're dealing with really ragged input data:

use 5.010; # for // operator use warnings; use strict; use Data::Dump; use Test::More # tests => ?? + 1 # Test::NoWarnings adds 1 test 'no_plan' ; use Test::NoWarnings; my @totals; while (my $line = <DATA>) { chomp $line; my @fields = split ' ', $line; for my $i (0 .. $#fields) { # $totals[$i] = $fields[$i] + (defined($totals[$i]) ? $totals[$i +] : 0); $totals[$i] = $fields[$i] + ($totals[$i] // 0); } # dd \@fields; dd\@totals; # FOR DEBUG } my $max_input_cols = @totals; ok $max_input_cols == 5, qq{max number input columns}; is_deeply \@totals, [ 21, 176, 909, 6006, 20002 ], qq{column totals}; printf qq{max cols in input data: %d \n}, $max_input_cols; print qq{column totals: \n}; printf qq{%6d}, $_ for 0 .. $#totals; print qq{\n}; for my $col (@totals) { printf qq{%6d}, $col; } print qq{\n}; __DATA__ 1 11 2 22 202 2002 20002 3 33 303 4 44 404 4004 5 6 66

Output:

c:\@Work\Perl\monks\Anonymous Monk\1077543>perl ragged_field_summation +_1.pl ok 1 - max number input columns ok 2 - column totals max cols in input data: 5 column totals: 0 1 2 3 4 21 176 909 6006 20002 ok 3 - no warnings 1..3

In reply to Re: How can you make this script general? by AnomalousMonk
in thread How can you make this script general? by Anonymous Monk

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.