我有一个包含数字列的文件:
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行的数字总和。所以对于column2我想总和15.2,7.0和1.0。对于column3,我想总结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,输出错误:
1
5
.
2
7
.
0
0
.
0
etc
期望的输出:
c2=23.2
c3=14.5
答案 0 :(得分:2)
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
答案 1 :(得分:0)
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];
}
}
答案 2 :(得分:0)
#!/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