[英]Split a column then sum and push sum onto array in perl
I have a file that looks like this: 我有一个看起来像这样的文件:
LOCUS POS ALIAS VAR TEST P I DESC
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 1 0.43 0/1
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 1 0.295 0/1
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 1 0.005 1/1
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 0.676617 0.005 1/0
I want to split the last field by "/", then sum those numbers, and push another column on with the sum. 我想将最后一个字段除以“ /”,然后将这些数字求和,然后将总和推到另一列。 For example, I would want the output to look like: 例如,我希望输出看起来像:
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 1 0.43 0/1 1
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 1 0.295 0/1 1
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 1 0.005 1/1 2
CCL23|disruptive chr17:34340329..34340854 . 2 BURDEN 0.676617 0.005 1/0 1
I have this code, but it doesn't work: 我有以下代码,但它不起作用:
#! perl -w
my $file1 = shift@ARGV;
my $NVAR=0;
my @vars;
open (IN, $file1) or die "couldn't read file one";
while(<IN>){
my@L=split;
next if ($L[0] =~ m/LOCUS/);
my@counts=split /\//, $L[7];
foreach (@counts){
$NVAR=${$_}[0] + ${$_}[1];
}
push @vars,[$L[0],$L[1],$L[2],$L[3],$L[4],$L[5],$L[6],$L[7],$NVAR];
}
close IN;
print "LOCUS POS ALIAS NVAR TEST P I DESC SUM\n";
foreach(@vars){
print "@{$_}\n";
}
Any help is appreciated. 任何帮助表示赞赏。
Always include use strict;
始终包括use strict;
and use warnings;
并use warnings;
at the top of EVERY script. 在每个脚本的顶部。
Limit your variables to the smallest scope possible, as declaring $NVAR
outside of the while
loop introduced a bug. 将变量限制在最小范围内,因为在while
循环之外声明$NVAR
引入一个错误。 Your summation can be fixed by the following: 您的总和可以通过以下方式固定:
my $NVAR = 0;
foreach (@counts){
#$NVAR=${$_}[0] + ${$_}[1]; <-- this was bad.
$NVAR += $_;
}
However, this can be solved using a perl oneliner 但是,可以使用perl oneliner解决此问题
perl -MList::Util=sum -lane 'push @F, sum split "/", $F[-1]; print "@F"' file.txt
Or if you have a header row: 或者,如果您有标题行:
perl -MList::Util=sum -lane '
push @F, $. == 1 ? "SUM" : sum split "/", $F[-1];
print "@F"
' file.txt
Note, you can also utilize List::Util sum
in your script as well. 注意,您也可以在脚本中使用List::Util sum
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.