Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 26th, 2012  |  syntax: None  |  size: 1.59 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How can I output unique, count and sum using perl
  2. 08/2009   I-111   300
  3. 08/2009   I-112   400
  4. 08/2009   I-113   500
  5. 10/2009   I-200   1000
  6. 10/2009   I-300   500
  7. 11/2009   I-300   100
  8. 11/2009   I-100   400
  9.        
  10. 08/2009 3 1200
  11. 10/2009 2 1500
  12.        
  13. use List::MoreUtils 'uniq';
  14. my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4;    # (1,2,3,5,4)
  15.        
  16. my @array = (5,6,7,8);
  17. my $a_count = @array;       # 4
  18.  
  19. my %hash = ('x' => 1, 'y' => 2);
  20. my $h_count = keys %hash;   # 2
  21.        
  22. use List::Util 'sum';
  23. my @array = (1,2,3,4,5);
  24. print sum @array;   # 15
  25.        
  26. #!/usr/bin/perl
  27. use strict;
  28. use warnings;
  29. use Data::Dump qw(dump);
  30.  
  31. my %h;
  32. while(<DATA>) {
  33.     chomp;
  34.     my @el = split;
  35.     $h{$el[0]}{count}++;
  36.     $h{$el[0]}{sum} += $el[2];
  37. }
  38. dump%h;
  39.  
  40. __DATA__
  41. 08/2009   I-111   300
  42. 08/2009   I-112   400
  43. 08/2009   I-113   500
  44. 10/2009   I-200   1000
  45. 10/2009   I-300   500
  46. 11/2009   I-300   100
  47. 11/2009   I-100   400
  48.        
  49. (
  50.   "08/2009",
  51.   { count => 3, sum => 1200 },
  52.   "11/2009",
  53.   { count => 2, sum => 500 },
  54.   "10/2009",
  55.   { count => 2, sum => 1500 },
  56. )
  57.        
  58. use Data::Dumper;
  59. print Dumper %h;
  60.        
  61. while (my ($key, $values) = each %h) {
  62.     print "$key $values->{count} $values->{sum}n";
  63. }
  64.        
  65. #!/usr/bin/perl
  66. use strict;
  67. use warnings;
  68.  
  69. my %h;
  70. while(<DATA>) {
  71.     chomp;
  72.     my @el = split;
  73.     $h{$el[0]}->{count}++;
  74.     $h{$el[0]}->{sum} += $el[2];
  75. }
  76.  
  77. foreach my $element (sort keys %h) {
  78.     printf "%-10.10s  %-6.6s  %4dn", $element,
  79.     $h{$element}->{count}, $h{$element}->{sum};
  80. }
  81. __DATA__
  82. 08/2009   I-111   300
  83. 08/2009   I-112   400
  84. 08/2009   I-113   500
  85. 10/2009   I-200   1000
  86. 10/2009   I-300   500
  87. 11/2009   I-300   100
  88. 11/2009   I-100   400