## sorting a hash using its value

Expand Messages
• I m having difficulty in getting the first 3 highest values in a hash, can somebody help me (spending many hours, figuring this out) e.g %hash=( 1= 2, 2= 10,
Message 1 of 2 , Jul 2, 2003
I'm having difficulty in getting the first 3 highest values in a hash, can
somebody help me (spending many hours, figuring this out)
e.g
%hash=(
1=>2,
2=>10,
3=>4,
4=>3,
5=>12
);

I want to get only the values 12, 10 & 4. This actually came from test
data, one column is the bin number(which is unique) and
another column(which is the count), then from this two parameters, I
created a hash (like the example above), the bin number
is the key and count is the value..

Thanks..

BRgds,
--
Richard Bornay
Test Product Engineering
Test Data Management Group
ST Assembly Test Services
6824-1367

[Non-text portions of this message have been removed]
• ... hash, can ... Use values( %hash ) It returns a list of the values from the hash. So, this untested code might work: # The \$a \$b does a numeric sort
Message 2 of 2 , Jul 2, 2003
--- In perl-beginner@yahoogroups.com, richardb@s... wrote:
> I'm having difficulty in getting the first 3 highest values in a
hash, can
> somebody help me (spending many hours, figuring this out)
> e.g
> %hash=(
> 1=>2,
> 2=>10,
> 3=>4,
> 4=>3,
> 5=>12
> );
>
> I want to get only the values 12, 10 & 4. This actually came from test
> data, one column is the bin number(which is unique) and
> another column(which is the count), then from this two parameters, I
> created a hash (like the example above), the bin number
> is the key and count is the value..
>
>
> Thanks..
>
>
>
> BRgds,
> --
> Richard Bornay
> Test Product Engineering
> Test Data Management Group
> ST Assembly Test Services
> 6824-1367
>
> [Non-text portions of this message have been removed]

Use 'values( %hash )'
It returns a list of the values from the hash.

So, this untested code might work:
# The '\$a <=> \$b' does a numeric sort of the values.
my @SortedList = sort { \$a <=> \$b } values %hash;
# Drop elements 3+ i.e. keep top 3 values.
splice( @SortedList, 2 );
Your message has been successfully submitted and would be delivered to recipients shortly.