in reply to Query of multi dimentional array
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my @content = (<DATA>); my $no_of_seq = scalar(@content); my @myArray; for my $row (@content) { my @columns = split ' ', $row; push @myArray, \@columns; } say join "\t", $myArray[0][0], 'sum'; my $width = $#{ $myArray[0] }; for (my $row = 1; $row < $no_of_seq; $row++){ print $myArray[$row][0], "\t"; my $sum = 0; for my $col (@{ $myArray[$row] }[1 .. $width]) { $sum += $col; } say $sum; } __DATA__ GeneID Tp1 Tp2 Tp3 ALA1 10 12 11 THR8 57 99 12 HUA4 100 177 199 ABA5 2 5 10
Update: But, to compute a sum of a row, you don't need the other rows, so you can process the file line by line, no need to store it into an array. List::Util already exports the sum sub, no need to compute it yourself.
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use List::Util qw{ sum }; <DATA>; # ignore the first line; say "GeneID\tSum"; while (<DATA>) { my @cols = split ' '; my $sum = sum(@cols[1 .. $#cols]); say join "\t", $cols[0], $sum; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Query of multi dimentional array
by bliako (Abbot) on Mar 26, 2020 at 10:43 UTC |