简体   繁体   English

如何使用Perl输出唯一,计数和总和

[英]How can I output unique, count and sum using perl

I am new to Perl. 我是Perl的新手。 I need to find the unique, count and sum for the following data. 我需要找到以下数据的唯一,计数和总和。 I request your help. 我请求你的帮助。

08/2009   I-111   300
08/2009   I-112   400
08/2009   I-113   500
10/2009   I-200   1000
10/2009   I-300   500
11/2009   I-300   100
11/2009   I-100   400

So I need to find like this 所以我需要找到这样的

08/2009 3 1200
10/2009 2 1500

uniq from List::MoreUtils returns the unique elements of a list: List::MoreUtils uniq返回List::MoreUtils的唯一元素:

use List::MoreUtils 'uniq';
my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4;    # (1,2,3,5,4)

A list expression in scalar context returns the number of elements. 标量上下文中的列表表达式返回元素数。

my @array = (5,6,7,8);
my $a_count = @array;       # 4

my %hash = ('x' => 1, 'y' => 2);
my $h_count = keys %hash;   # 2

sum from List::Util adds the elements of a list. List::Util sum添加List::Util的元素。

use List::Util 'sum';
my @array = (1,2,3,4,5);
print sum @array;   # 15

Not sure what you want exactly, but is this ok? 不确定您到底想要什么,但是可以吗?

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dump);

my %h;
while(<DATA>) {
    chomp;
    my @el = split;
    $h{$el[0]}{count}++;
    $h{$el[0]}{sum} += $el[2];
}
dump%h;

__DATA__
08/2009   I-111   300
08/2009   I-112   400
08/2009   I-113   500
10/2009   I-200   1000
10/2009   I-300   500
11/2009   I-300   100
11/2009   I-100   400

output: 输出:

(
  "08/2009",
  { count => 3, sum => 1200 },
  "11/2009",
  { count => 2, sum => 500 },
  "10/2009",
  { count => 2, sum => 1500 },
)

Re: M42's answer, try: 回复:M42的回答,试试:

use Data::Dumper;
print Dumper \%h;

Or you could just write: 或者你可以写:

while (my ($key, $values) = each %h) {
    print "$key $values->{count} $values->{sum}\n";
}

Normally, I don't do Write my program for free type stuff, but since M42 already did most of it, here's it is without the Data::Dump : 通常情况下,我不会为自由类型的东西编写我的程序 ,但是因为M42已经完成了大部分工作,所以这里没有Data::Dump

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

my %h;
while(<DATA>) {
    chomp;
    my @el = split;
    $h{$el[0]}->{count}++;
    $h{$el[0]}->{sum} += $el[2];
}

foreach my $element (sort keys %h) {
    printf "%-10.10s  %-6.6s  %4d\n", $element, 
    $h{$element}->{count}, $h{$element}->{sum};
}
__DATA__
08/2009   I-111   300
08/2009   I-112   400
08/2009   I-113   500
10/2009   I-200   1000
10/2009   I-300   500
11/2009   I-300   100
11/2009   I-100   400   

Now learn yourself some Perl ! 现在学习一些Perl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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