-1

可能重复:
如何使用 perl 输出唯一、计数和求和

如何在 perl 中获取唯一值、计数值和求和值?我的代码如下:

   while (<$input>) {
               chomp;
               my($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19,$f20,$f21,$f22,$f23,$f24,$f25) = split(/\|/);
             $f24  = " " if !defined($f24);

             push @ff4, qw($f4); # VEN 10/19/11

             push @fff4, $f4, $f16, $f7; # VEN 10/28/11
             ..... ....... ...... ........ ......
             ..... ....... ...... ....... .......
    my %count;
    map { $count{$_} ++ } @array;
    my@count = map { "$_ ==========> ${count{$_}}\n"} sort keys (%count);

    #print $output2 sprintf("@count\n");


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

    print $output2 %h;

我得到这样的输出

       08/2009 ====> 2030
       08/2010 ====> 2300
       09/2010 =====> 1500

但我必须像这样得到它:

      08/2009 ====> 2
      08/2010 ====> 3
      09/2010 =====> 5

我在 Solaris 上使用 Perl

4

1 回答 1

0
  1. 您的代码根本不起作用。如果您只发布不相交的不相关块,我们无法告诉您如何修复它。

  2. 要获取数组的唯一元素,请使用List::MoreUtil模块的uniq()方法。

    要计算它们,请使用scalar(@array)或简单地将数组放入标量上下文中。

    总结一下,使用List::Util模块的sum()方法

  3. 如果您不想使用标准 CPAN 模块,可以使用foreach循环:

    my @array = (1, 2, 3, 4, 1, 4);
    my %unique = map { $_ => 1 } @array; # keys will be unique now
    my @unique = sort keys %unique;
    my $count = scalar(@unique);
    my $sum = 0;
    $sum += $_ foreach @unique;
    
于 2011-10-31T14:18:25.510 回答