添加数组列表 perl
我有一个文本文件,其中包含由空行分隔的数字列表,如下所示- 我想添加所有第一个 (20.187+19.715+20.706...) 、第二个元素 (15.415+14.726+15.777) 等等 要获得第一个、第二个、第三个等每个元素的总和,
20.187 15.415 8.663 6.001 6.565 6.459 6.564 ..
19.715 14.726 8.307 5.833 6.367 6.089 6.444 ..
20.706 15.777 9.185 6.546 7.327 7.172 7.084 ...
因为它们*没有按列排列*我如何将数组的元素相加。
I have a text file with list of numbers separated by blank line as given below-
i want to add all the first (20.187+19.715+20.706...) , second elements (15.415+14.726+15.777) and so on
to get the total of each element 1st,2nd,3rd etc
20.187 15.415 8.663 6.001 6.565 6.459 6.564 ..
19.715 14.726 8.307 5.833 6.367 6.089 6.444 ..
20.706 15.777 9.185 6.546 7.327 7.172 7.084 ...
since they are *not arranged in columns* how could i add up the elements of the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
split
获取所有字段。跟踪数组中的运行总计(其索引映射到文件中的列)。像这样的事情:
请注意,默认情况下
split
在空格上拆分。如果您愿意,可以使用其他分隔符。编辑:遗憾的是,既然问题已经澄清,这个答案毫无用处。请改用布莱恩·罗奇的答案。
Use
split
to get all the fields. Keep track of a running total in an array (the indexed of which being mapped to the columns in your file).Something like this:
Note that
split
splits on whitespace by default. You can use other delimiters if you like.EDIT: This answer is sadly useless, now that the question has been clarified. Use Brian Roach's answer instead.
编辑:从澄清的问题来看,需要处理空行以及一系列数字被分成多行的可能性。
这应该可以满足您的要求。您需要不断添加到 currentVals 数组中,直到遇到空行,然后进行数学计算。
EDIT: From the clarified question, Need to deal with the blank lines and the possibility that a series of numbers is broken onto multiple lines.
This should do what you're looking for. You need to keep adding onto the currentVals array until you hit a blank line, then do the math.
您可以尝试这样的操作:
$sum[$i]
将包含列$i
的总计。或者,稍微“毁灭”一点:
You could try something like this:
$sum[$i]
will contain the total of column$i
.Or, slightly more 'perlish':