http://www.perlmonks.org?node_id=1077543

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

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";