在Perl中添加数字列
我有一个包含数字列的文件:在Perl中添加数字列,perl,Perl,我有一个包含数字列的文件: 1 0.0 0.0 2 0.0 0.0 3 15.2 0.0 4 7.0 9.0 5 0.0 3.0 6 1.0 0.0 7 0.0 2.5 8 0 0 0 0 我需要找到右边两列第3行到第7行的数字之和。对于第2列,我想求和15.2,7.0和1.0。对于第3列,我想求和9.0、3.0和2.5。我需要保持单小数点格式 code: While (<INPUT>)
1 0.0 0.0
2 0.0 0.0
3 15.2 0.0
4 7.0 9.0
5 0.0 3.0
6 1.0 0.0
7 0.0 2.5
8 0 0 0 0
我需要找到右边两列第3行到第7行的数字之和。对于第2列,我想求和15.2,7.0和1.0。对于第3列,我想求和9.0、3.0和2.5。我需要保持单小数点格式
code:
While (<INPUT>){
my @a = split;
my $c2 .= $a[1];
my $c3 .= $a[2];
my $c2_string = substr($c2, 2, 5);
my $c3_string = substr($c3, 2, 5);
my @sumarray = split ('', $c2);
#then loop through each element and add them up.
期望输出:
c2=23.2
c3=14.5
并且这个不会为整个文件创建数组:
my ($sum2, $sum3);
while (<INPUT>) {
my @v = split;
if ($v[0] > 2 && $v[0] < 8) {
$sum2 += $v[1];
$sum3 += $v[2];
}
}
而似乎错误的结果是,什么?用不完整的代码很难复制。@FlyingFrog perl-Mstrict-we'my$x=my$y=0;'如果我只想知道从第3行到第4行的总数,那就不会给出正确的总数。我不想把所有的行加起来。只是行的特定范围。
my @data;
while (<INPUT>) {
push @data, [ split ];
}
my ($sum2, $sum3);
for (my $i = 2; $i < 7; $i++) {
$sum2 += $data[$i][1];
$sum3 += $data[$i][2];
}
print "$sum2, $sum3\n";
23.2, 14.5
my ($sum2, $sum3);
while (<INPUT>) {
my @v = split;
if ($v[0] > 2 && $v[0] < 8) {
$sum2 += $v[1];
$sum3 += $v[2];
}
}
#!/usr/bin/perl -w
use strict;
my $infile = 'in.txt';
open my $input, '<', $infile or die "Can't open to $infile: $!";
my ($col1, $sum_col2, $sum_col3 );
while (<$input>) {
my (@cols) = split;
$col1 = $cols[0];
$sum_col2 += $cols[1] if $col1 == 3 .. 7;
$sum_col3 += $cols[2] if $col1 == 3 .. 7;
}
print "Column2: $sum_col2\n";
print "Column3: $sum_col3\n";
Column2: 23.2
Column3: 14.5
my $x = my $y = 0;
while (<INPUT>) {
my @a = split;
($a[0] >=3 and $a[0] <=7) or next;
$x += $a[1];
$y += $a[2];
}
print "c2=$x\n", "c3=$y\n";
perl -lane'
($F[0] >=3 and $F[0] <=7) or next;
$x += $F[1]; $y += $F[2];
END{ print for "c2=$x","c3=$y" }
' file