in reply to How can you make this script general?

As a one-liner

C:\test>perl -F\t -anle"$sums[$_]+=$F[$_] for 0 .. $#F; }{ printf qq[C +olumn:%u total:%u\n], $_, $sums[$_] for 0 .. $#sums" 1 2 3 4 5 6 7 8 9 ^Z Column:0 total:12 Column:1 total:15 Column:2 total:18

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.

Replies are listed 'Best First'.
Re^2: How can you make this script general?
by Anonymous Monk on Mar 08, 2014 at 19:27 UTC
    I made it like this:
    #The idea is to read the first line of the file and see how many colum +ns we have, then we proceed accordingly, column-by-column open (INFILE10, '<', 'ex1.dat') or die "File ex1.dat does not exist!\n +"; my $firstLine = <INFILE10>; close INFILE10; my @array_firstLine=split(/\t/, $firstLine); my $total_columns=scalar(@array_firstLine); print "This file has $total_columns columns in total.\n"; for(my $k=1; $k<=$total_columns; $k++) { print "Calculate sum for column $k\n"; my $wanted_column_number=$k; #this is the column that we want to +sum up each time, until we finish the columns my $sum_of_column=0; open (INFILE10, '<', 'ex1.dat') or die "File ex1.dat does not exist! +\n"; while( my $line10 = <INFILE10>) { my @split_line10 = split(/\t/, $line10); my $respective_element = $split_line10[$k-1]; $sum_of_column = $sum_of_column + $respective_element; } close INFILE10; print "The sum for column $k is: $sum_of_column.\n"; }
      mate you're wrong,
      with perl you don't have to do any of what you're doing.
      while(@a = split /\t/, <DATA>){ $b[$_] += $a[$_] for 0..$#a; } print "@b\n"; __DATA__ 1 2 3 4 5 6 7 8 9 10 11 12