簡體   English   中英

添加數組列表perl

[英]adding array list 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 ...

由於它們不是按列排列的,所以我該如何添加數組的元素。

使用split獲取所有字段。 跟蹤數組中的運行總計(其索引已映射到文件中的列)。

像這樣:

while (<$file>)
{
  chomp;
  my $index = 0;
  $total[$index++] += $_ for split;
}

請注意,默認情況下, split在空白處進行分割。 如果願意,可以使用其他定界符。


編輯:可悲的是,既然這個問題已經得到澄清,這個答案是無用的。 請改用Brian Roach的答案。

編輯:從一個澄清的問題,需要處理空白行和一系列數字被分解成多行的可能性。

my @totals;
my @currentVals;

while (my $line = <FILE>)
{
    chomp($line);
    if ($line eq "")
    {
        for ($i = 0; $i < @currentVals; $i++)
        {
            @totals[$i] += @currentVals[$i];
        }    
        @currentVals = ();
    }
    else
    {
        push @currentVals,  split(' ', $line);
    }

}

這應該做您想要的。 您需要繼續添加到currentVals數組中,直到碰到空白行,然后進行數學運算。

use strict;
use warnings;

# Paragraph mode (so that blank lines become our input delimiter).
local $/ = "\n\n";

my @totals;

while (<>){
    my $i;
    $totals[$i++] += $_ for split;
}

您可以嘗試這樣的事情:

my @sum;
while (<>) {
    chomp;
    my @items = split /\s+/;
    for (my $i=0; $i<@items; $i++) {
        $sum[$i] += $items[$i];
    }
}

$sum[$i]將包含列$i的總數。

或者,稍微“​​完成”:

my @sum;
while (<>) {
    chomp;
    my @items = split;
    for my $i (0 .. $#items) {
        $sum[$i] += $items[$i];
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM