On 2011-03-12 13:17, ashwin ts wrote:
Hi,

Hello,

I have an array which has few elements like '1,2,3,4,2,3,1,2,1,1,1,4,6,7'
i need to know how many times each element has occurred in the same array.
for example 1-5 times
                 2-3 times...

Use a hash.

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

    my @array = (1, 1, 2, 4, 2, 1, 9, 42, 0, 0, 0, 1, 0, 0, 2);

    my %count;
    $count{$_}++ for @array;

    for my $c( sort{ $b <=> $a } keys(%count) ) {
      printf("% 3d appeared %d times\n", $c, $count{$c});
    }

Output:

     42 appeared 1 times
      9 appeared 1 times
      4 appeared 1 times
      2 appeared 3 times
      1 appeared 4 times
      0 appeared 5 times


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to