in reply to extract number of times a value appears in an array

Here's one way to do it. This way doesn't preserve original order, but it does sort the frequency list based on the numerical order of the input list, which seems to be how your example data was sorted. Given your example input and output, my script produces the output list in the same order your example demonstrated.

I would think it would be more useful to maintain a key/value relationship so that instead of only ending up with a list of frequencies, you would end up with a set of item/frequency pairs. My solution could be easily adapted to do that instead, should your specification change to include that requirment.

use strict; use warnings; my @items = ( 1, 3, 3, 3, 5, 5, 5, 5 ); my @frequency = @{ frequency( \@items ) }; print "@frequency\n"; sub frequency { my $items_ref = shift; my %counter; $counter{$_}++ for @{$items_ref}; return [ map { $counter{$_} } sort { $a <=> $b } keys %counter ]; }

Dave