Myrddin Emrys has asked for the wisdom of the Perl Monks concerning the following question:

I've got an array of names and I want to be able to tell how many times each name shows up in the array.

For example, if I had: (I have a bigger array though) @names = {Tom, Dick, Harry, Tom} I would like to output something like:

Tom = 2 Dick = 1 Harry = 1
Is there an easy bit of code to do this?

Help please,
Myrddin

Edit by tye to preserve formatting and change title from "Manipulating Arrays"

Replies are listed 'Best First'.
Re: Counting repeated values from an array
by grinder (Bishop) on Jul 31, 2001 at 01:21 UTC
    Sure, you want to run the array through a hash to count the occurrences of each element

    my %count; foreach my $element( @name ) { ++$count{$element}; } foreach my $element( keys %count ) { print "$element = $count{$element}\n"; }

    If you want to sort the names alphabetically, use foreach my $element( sort keys %count). If you want to sort by highest count first, use foreach my $element( sort { $count{$b} <=> $count{$a} } )

    Do yourself a favour and invest in the Perl Cookbook. It's chock full of useful Perl idioms like this. It's money well spent -- and the only Perl title that never moves far from my console.

    update: changed the title of this node to reflect that of the parent node.

    --
    g r i n d e r
(ichimunki) Re: Manipulating Arrays
by ichimunki (Priest) on Jul 31, 2001 at 01:20 UTC
    foreach (@names) {$count{$_}++;} foreach (keys %count) {print "$_ = ".$count{$_}."\n";}
Re: Manipulating Arrays
by damian1301 (Curate) on Jul 31, 2001 at 01:38 UTC
    A more of a golfed response.
    @names=qw/tom tom tom green/; my%h;%_=map{$h{$_}++}@names;map{print"$_=",$h{$_},"\n"}keys%h;


    $_.=($=+(6<<1));print(chr(my$a=$_));$^H=$_+$_;$_=$^H; print chr($_-39); # Easy but its ok.
      Or... without some maps:
      my @names=qw/tom tom tom green/; $_{$_}++for@names;print"$_=$_{$_}\n"for keys%_;

      GreetZ!,
        ChOas

      print "profeth still\n" if /bird|devil/;
Re: Manipulating Arrays
by dsb (Chaplain) on Jul 31, 2001 at 01:20 UTC
    Post the code that you have already, so we can help you rather than tell you...if you don't have any code then take an honest shot at it and come back with the errors or unexpected results you are getting.

    I think you'll find that you learn a lot more if you learn from your own mistakes rather than just ask for answers...

    Good luck. ;)

    Amel - f.k.a. - kel