-1

Possible Duplicate:
How can I output unique, count and sum using perl

How can I get unique, count and sum values in perl? My code is as follows:

   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;

I am getting output like this

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

But I have to get it like this:

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

I am using Perl on Solaris

Community
  • 1
  • 1
user1016594
  • 71
  • 1
  • 1
  • 2
  • 2
    Can you please post WORKING code? `@array` is never assigned to before you use it in `map` – DVK Oct 31 '11 at 14:15
  • 1
    Why `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(/\|/);`? Why not simply create an array? `@f = $_`. Then, you can use `$f[23]` instead of `$f24`. – David W. Oct 31 '11 at 15:11

1 Answers1

0
  1. Your code doesn't work at all. We can't tell you how to fix it if you only post disjoint unrelated chunks.

  2. To get unique elements of array, use List::MoreUtil module's uniq() method.

    To count them, use scalar(@array) or simply put an array into scalar context.

    To sum them up, use List::Util module's sum() method

  3. If you don't want to use standard CPAN modules, you can use a foreach loop:

    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;
    
DVK
  • 126,886
  • 32
  • 213
  • 327
  • Hi Thanks for your email. But ur code is giving count as 6. But I want count as 1-->2, 2-1,3-1,4-2 Pl.help me out.Thanks – user1016594 Oct 31 '11 at 16:07