Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How do I print the number of unique occurrences of an element array and also print the percentage of the occurrences, like: @data=(string1, string1, string1,string2,string2,string3); print will be something like: Number of entries 3(unique strings) it represents 50% of 6 occurrences.

Replies are listed 'Best First'.
Re: Array statistics
by erikharrison (Deacon) on Jun 26, 2002 at 20:53 UTC

    Generally, here on perlmonks, it's a good idea to show your code. We're all more inclined to help you if you show what you've been doing, to prove that you've done your homework. In this vein, here are a couple of links:

    But, as long as you took the time to post the question, here is one of the many ways you might do it.

    foreach $item (@data) { $members{$item}++; } foreach $item (keys %members) { print "$item : $members{$item}"; }
    Cheers,
    Erik

    Light a man a fire, he's warm for a day. Catch a man on fire, and he's warm for the rest of his life. - Terry Pratchet

Re: Array statistics
by mfriedman (Monk) on Jun 26, 2002 at 21:53 UTC
    To count the occurrance of things in your array:

    my @array = ('foo', 'foo', 'bar', 'foo', 'bar', 'baz'); my %count; $count{$_}++ for @array; for(sort(keys(%count))) { print "$_: $count{$_}\n"; }

    I'm sure you can work out how to then calculate the percentages.

Re: Array statistics
by thunders (Priest) on Jun 26, 2002 at 20:56 UTC
    Well I imagine you would want to divide the number of occurances of each thing by the total number of things. Unfortunately I don't think anyone on this site could tell you how to do this, unless you are willing to thank perlmonks.com on your homework sheet.
Re: Array statistics
by bronto (Priest) on Jun 27, 2002 at 08:11 UTC
    my @data = &initialize_it_the_way_you_want() ; my $total = @data ; # or scalar @data, explicitly die "give me arguments!" unless $total ; my %count ; my %perc ; map $count{$_}++,@data ; map { $perc{$_} = $count{$_}/$total } keys %count ; # Now you have recurrence counts on %count and # percentages on %perc to do whatever you want.

    Ciao!
    --bronto

    # Another Perl edition of a song:
    # The End, by The Beatles
    END {
      $you->take($love) eq $you->made($love) ;
    }