简体   繁体   中英

adding array list perl

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.

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:

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

Note that split splits on whitespace by default. You can use other delimiters if you like.


This answer is sadly useless, now that the question has been clarified. 可悲的是,既然这个问题已经得到澄清,这个答案是无用的。 Use Brian Roach's answer instead.

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.

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);
    }

}

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.

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;
}

You could try something like this:

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

$sum[$i] will contain the total of column $i .

Or, slightly more 'perlish':

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM