in reply to Splicing and Sorting problem with Tie::IxHash

Hello, I don't see excatly what you are trying to do (still morning here ...).
But to print out just the top two keys of your hash based on the value
I would use something like this:
use warnings; use strict; my %hash = ( '1-1' => 80, '1-4' => 26, '4-4' => 3, '2-2' => 180, '2-4' => 72, '1-2' => 2196 ); my $count=1; foreach my $key (sort{$hash{$b}<=>$hash{$a}} keys %hash ) { print "$key : $hash{$key}\n" ; last if $count++ > 1; }

hth, si_lence

Replies are listed 'Best First'.
Re^2: Splicing and Sorting problem with Tie::IxHash
by monkfan (Curate) on Oct 06, 2004 at 07:57 UTC
    Hi,
    Thanks for the reply.

    But,I need top-'N' values,
    and still keep it as a hash.
      OK. In this case I think you can make it without the tied hash.
      You will have to sort the output in printhash (as you did)
      to get them in descending order.
      si_lence
      %hash = ( '1-1' => 80, '1-4' => 26, '4-4' => 3, '2-2' => 180, '2-4' => 72, '1-2' => 2196 ); $N =2; %hash = seq_score($N,%hash); printhash(%hash); #---sub----- sub seq_score{ my %spair; ($N,%spair) = @_; my %topN_pair = (); my %seq =(); my $count=1; foreach my $key (sort{$spair{$b}<=>$spair{$a}} keys %spair ) { $topN_pair{$key}=$spair{$key}; last if $count++ >= $N; } return %topN_pair; } sub printhash { my %hash = @_; foreach my $key (sort{$hash{$b}<=>$hash{$a}} keys %hash ) { print $key, ":", $hash{$key}, "\n" } }