Hello!
I have this script that calculates the sum of each column in a tab-separated file. My problem is that I would like to make it work even if I don't know how many columns I have, i.e. somehow create the arrays dynamically based on number of columns perhaps...Can you help me?
my @split_array9=(); my @split_array9_col1=(); my @split_array9_col2=(); my @split_array9_col3=(); open (INFILE9, '<', 'ex1.dat'); while( my $line9 = <INFILE9>) { my @split_line9 = split(/\t/, $line9); my $element_col_1 = $split_line9[0]; my $element_col_2 = $split_line9[1]; my $element_col_3 = $split_line9[2]; push (@split_array9_col1, $element_col_1); push (@split_array9_col2, $element_col_2); push (@split_array9_col3, $element_col_3); } close INFILE9; #calculate the sums for each column based on each of the arrays my $sum_col1=0; my $sum_col2=0; my $sum_col3=0; for (my $w=0; $w<=$#split_array9_col1; $w++) { $sum_col1 = $sum_col1 + $split_array9_col1[$w]; } for (my $y=0; $y<=$#split_array9_col2; $y++) { $sum_col2 = $sum_col2 + $split_array9_col2[$y]; } for (my $z=0; $z<=$#split_array9_col3; $z++) { $sum_col3 = $sum_col3 + $split_array9_col3[$z]; } print "The sum for column 1 is: $sum_col1, the sum for column 2 is: $s +um_col2 and the sum for column 3 is: $sum_col3.\n";

In reply to 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.