arrays - 弹出数组的键以计算总数

标签 arrays perl file-io

我试图简单地弹出每个数字值并将它们加在一起以获得总计。

输入文件:

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/

相关文章:

ruby - 如何在 Ruby 中一次读取一个文件字节?

c - 编译器如何在堆栈上使用默认值为零来初始化本地数组?

Javascript - 如何在 2 个数组之间循环?

将 Char* 转换为 Char* 数组

c++ - C++ STL 中动态容器的内存分配

perl - Bioperl:初学者的笔记或在线引用

perl - 运行时错误 "Can' t 修改非左值子例程”

perl - 在perl脚本中获取%AppData%的路径

php - 在 PHP 中,哪个更快——读取文件还是调用数据库?

python - 使用 numpy 或 pandas 处理长格式的 csv 文件