in reply to 2d Array - making an array for the column then adding the values

You say your problem is with extracting a column and summing it. That only takes one line (three without a module), so why did you present so much code?

use List::Util qw( sum ); my $sum = sum map { $array[$_][$col] } 0..$#array;
my $sum = 0; for my $row (0..$#array) { $sum += $array[$row][$col]; }

Please locate your problem, then come back if you can't fix it once you locate it.


By the way,

my $nextline = <FASTA>; if($nextline =~ /^(\S+)$/) { my $nextline = <FASTA>; if($nextline =~ /^\+(.*)\s/) { my $nextline = <FASTA>; if($nextline =~ /^(\S+)$/) { $qual = $1;
causes lines to be skipped if an "if" is ever false. You want redo. And the unused captures needlessly slow down your matches.
my $nextline = <FASTA>; redo if $nextline !~ /^\S+$/; $nextline = <FASTA>; redo if $nextline !~ /^\+/; $nextline = <FASTA>; redo if $nextline !~ /^\S+$/; chomp( my $qual = $nextline );

Replies are listed 'Best First'.
Re^2: 2d Array - making an array for the column then adding the values
by hansoffate (Novice) on Sep 21, 2009 at 02:30 UTC
    Thanks for your help. My PI doesn't want me to use any other modules other then the default ones that come installed with perl, so I can't use List::Util. I already have the the column assigned to a 1D array on line 121, but I believe it is all referenced. If I try to use this sub with a passed in @col, the total is calculated incorrectly.

    sub score_count { my @arr = shift; my $total = 0; foreach my $score (@arr) { print "@$score "; ##prints actual values; If @ taken out, +values printed are like ARRAY(0x95533e0) $total += @$score; ##if @ is taken out the summation is somewhe +re ~140915576; however, with the @, the values are still incorrect. } print "$total\n"; return $total; }
    Are you suggesting to not even use the column slice so it's a 1D array?

    Thanks for letting me know about if construct issue but I do want to skip the line if it is false so that code should be correct.

    Thanks for the help

      List::Util does come with Perl.

      Thanks for isolating the problem. I was explaining it here while you were writing your post.

      The only thing I didn't cover is that references evaluate to the address of the referenced item when they are treated as a number.

      My PI doesn't want me to use any other modules other then the default ones that come installed with perl, so I can't use List::Util.
      Firstly, List::Util is a core module, which means that it is one of "the default ones that come installed with perl". Feel free to use it, just as you are using Getopt::Std. Update: I didn't see ikegami's comment relating to this.

      Secondly, even if it were not a core module, you could reuse some of the module's source code. So, tell your PI (whatever that is) to put that in his pipe and smoke it!