in reply to how to print top 5 elements from a hash

How about this?
#!/usr/bin/perl use strict; my %hash = ( 'a' => '1', 'b' => '2', 'c' => '3', 'f' => '6', 'e' => '5', 'd' => '4' ); my $count = 0; foreach my $i ( sort keys %hash ) { print "$i ==> $hash{$i}\n" if ($count <= 4); $count++; }

Replies are listed 'Best First'.
Re^2: how to print top 5 elements from a hash
by Marshall (Canon) on Jun 02, 2009 at 07:08 UTC
    This is good, but since (sort keys %hash) is a list, we can just take a list slice:
    my %hash = ( 'b' => '2', 'a' => '1', 'c' => '3', 'f' => '6', 'e' => '5', 'd' => '4' ); foreach my $key ( (sort keys %hash)[0..4] ) { print "$key ==> $hash{$key}\n" } #prints.. #a ==> 1 #b ==> 2 #c ==> 3 #d ==> 4 #e ==> 5