in reply to Re: How can you make this script general?
in thread How can you make this script general?

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

Replies are listed 'Best First'.
Re^3: How can you make this script general?
by Lennotoecom (Pilgrim) on Mar 08, 2014 at 20:07 UTC
    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