Friday, 15 April 2011

arrays - How to total the columns in a tab delimited file with unknown number of columns using split? -


I have a tab delimited file that looks:

  __ data 0 0 1 0 1 ... 1 1 0 0 0 ... 1 0 0 0 0 ... 0 1 1 1 1 ...  

There is an unspecified number of columns and rows. Columns can be as many as 5 - 20 +.

Currently I'm looking at "\ t" to read the file and split the lines.

Below is just a section of the required code, please note, I use strict and -W, and declare all the variables.

  open (IN, "../../Desktop/$out") or die "$ out can not be opened"; My @sams; While (& lt; IN & gt;) {if ($ _ = ~ / ([[01] \ t] *) /) {my @fields = partition / \ t /, $ 1; $ $ [$ I] + = $ field before my $ i ($ .. $ # field) [$ i]; }}} Print included ("\ n", @sums), "\ n";  

If you can come up with a better ideal method then I would be happy to try it. When I run it, I am coming with the following:

  __OUTPUT__ 0 1 1  

When I want to have the total in each column, To add an underneath each column, in the printable format, the sum total I have not used the partition function before, so this is an explanation of how to properly use it, and using this array (?) Thanks great!

  __ wantedOutput__ 2 2 2 1 2 ...  

Then the total for each column.

You're almost there to survive in the loop in the loop, before you start it Must have to declare. If you want output on one line, then join a new line, but with a tab:

  #! Use / usr / bin / perl warnings; Strict use; My @sams; While (& lt; DATA & gt;) {if (/ ^ [01] (?: \ T [01]) + $ / x) {my @fields = split; For my $ i (0 .. $ # field) {$ sum [$ i] + = $ fields [$ i]; }}} Print Add ("\ t", @sums), "\ n"; __DATA__ 0 0 1 0 1 1 1 0 0 0 1 0 0 0 1 1 1 1  

No comments:

Post a Comment