Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Query of multi dimentional array

by choroba (Archbishop)
on Mar 26, 2020 at 10:09 UTC ( #11114662=note: print w/replies, xml ) Need Help??


in reply to Query of multi dimentional array

$myArray[$row] is a reference to an array, you seem to be adding it to the actual numbers in the columns. That's why the values are so high. You can simplify the algorithm by iterating over the values rather than indices:
#!/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; }

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Query of multi dimentional array
by bliako (Parson) on Mar 26, 2020 at 10:43 UTC

    And just in case you wanted to search by GeneID (which is very likely in a next step):

    my %myArray; #my @myArray; my $GeneID = shift @columns; $myArray{$GeneID} = \@columns; #push @myA +rray, \@columns; # and how to calculate sum of each row for my $GeneID (sort keys %myArray){ # optionally sort to have a consi +stent view my $sum = 0; for my $colItem (@{$myArray{$GeneID}}){ $sum += $colItem; } print "sum for $GeneID: $sum\n"; }

    bw, bliako

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11114662]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2020-05-31 14:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (174 votes). Check out past polls.

    Notices?