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

Hi monks, I am trying to write a hash to calculate the frequency of itmes in an array. I have managed to get the code to print the array in order of frequency, but also want to calculate and print how often each item occurs - this is where i'm struggling. Can anyone help??
# heres a snippet # @items contains all the thing i want to calculate frequency of. print "Items: @items\n"; # determine the frequency of each item. Sort them in ascending order. my %freq; my $count; foreach $pair (@items) { $freq{$pair}++; } # next foreach not working - want to print no of each individual item foreach $pair (@items) { ++$count; } my @array = sort { $freq{$b} <=> $freq{$a} } keys %freq +; print "Sorted:@array\n"; print "Count:$count\n";

Replies are listed 'Best First'.
Re: calculating frequency of item in an array
by davorg (Chancellor) on Feb 27, 2003 at 10:31 UTC

    I think you want something like this:

    my %freq; $freq{$_}++ for @items; foreach (sort { $freq{$b} <=> $freq{$a} } keys %freq) { print "$_ : $freq{$_}\n"; }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg