我试图简单地弹出每个数字值并将它们加在一起以获得总计。
输入文件:
Samsung 46
RIM 16
Apple 87
Microsoft 30
我的代码编译了,但是只返回0:
open (UNITS, 'units.txt') || die "Can't open it $!";
my @lines = <UNITS>;
my $total = 0;
while (<UNITS>) {
chomp;
my $line = pop @lines;
$line += $total;
}
print $total;
最佳答案
如果您只是想通过while
遍历它们,则无需将所有行都包含到数组中。另外,您需要对每行进行split
以获得号码。
use warnings;
use strict;
open (UNITS, 'units.txt') || die "Can't open it $!";
my $total = 0;
while (<UNITS>) {
chomp;
my $num = (split)[1];
$total += $num;
}
print "$total\n";
__END__
179
关于arrays - 弹出数组的键以计算总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19961888/