如何根据来自不同哈希的键对哈希值求和?

时间:2012-02-07 15:57:48

标签: perl

不确定这是否是这个问题的正确标题,因为我是Perl的新手,但我有一个包含两列感兴趣的文本文件:

AB      Volume
100     280
137     250
150     375
100     100
100     600
137     200

我想根据AB#总结一下卷,结果是

AB     Instances     Volume
100    3              980
137    2              450
150    1              375

我到目前为止所做的只是在输出文件中显示不同的AB,但我很难得到体积计数的总和。

$isAB{$AB} = 1;
$isVolume{$Volume} =1;
$numAB{$AB}++;

print "AB\tInstances\tVolume\n";
for $AB (sort {$a<=>$b;} keys %numAB) {
        print "$AB\t$numAB{$AB}\n";
}

任何帮助将不胜感激!感谢

5 个答案:

答案 0 :(得分:6)

怎么样:

#!/usr/bin/perl 
use strict;
use warnings;
use 5.010;

my %res;
while(<DATA>) {
    chomp;
    my @fields = split;
    $res{$fields[0]}{instance}++;
    $res{$fields[0]}{volume} += $fields[1];
}

foreach(sort {$a<=>$b} keys(%res)) {
    say "$_\t$res{$_}{instance}\t$res{$_}{volume}";
}

__DATA__
100     280
137     250
150     375
100     100
100     600
137     200

<强>输出:

100 3   980
137 2   450
150 1   375

答案 1 :(得分:2)

一种方式:

infile的内容:

AB      Volume
100     280
137     250
150     375
100     100
100     600
137     200

script.pl的内容:

use warnings;
use strict;
use List::Util qw( sum );

## Check arguments.
die qq[Usage: perl $0 <input-file>\n] unless @ARGV == 1;

## Hash to save content of input file.
my (%ab);

while ( <> ) { 
    ## Split line. If number of fields is different from two, omit it
    ## and read next one.
    my @f = split;
    next unless @f == 2;

    ## In first line print header.
    if ( $. == 1 ) { 
        printf qq[%s\n], join qq[\t], $f[0], qq[Instances], $f[1];
        next;
    }   

    ## Save fields of line.
    push @{ $ab{ $f[0] } }, $f[1];
}

## Print to output.
for ( sort { $a <=> $b } keys %ab ) { 
    printf qq[%s\t%s\t%s\n], $_, scalar @{ $ab{ $_ } }, sum @{ $ab{ $_ } };
}

运行脚本:

perl script.pl infile

输出:

AB      Instances       Volume
100     3       980
137     2       450
150     1       375

答案 2 :(得分:1)

添加另一个哈希以跟踪总和

$sumAB{$AB} += $isAB{$AB};

然后在你的打印循环中

print "$AB\t$numAB{$AB}\t$sumAB{$AB}\n";

答案 3 :(得分:0)

我建议使用record like data structure

#!/usr/bin/perl -w
use strict;
use warnings;
use 5.010;

my %res;
while(<DATA>) {        
     (my $key, my $volume)= split;
     $res{$key}->{QUANTITY}++;
     $res{$key}->{VOLUME}+=$volume;

}

#use Data::Dumper;
#print Dumper(%res);

for my $key (sort {$a<=>$b} keys %res){
    my $quantity=$res{$key}->{QUANTITY};
    my $volume=$res{$key}->{VOLUME};
    say join("\t",$key, $quantity,$volume);

}


__DATA__
100     280
137     250
150     375
100     100
100     600
137     200

答案 4 :(得分:0)

欢迎使用富有表现力的语言。对于这样的事情,我建议List::Pairwise

my %sums;
List::Pairwise::mapp { $sums{ $a } += $b } %numAB;
相关问题