in reply to Selection of Hash key value pairs

The easiest way would be like this:

use strict; my %hash = ( a_one => 1, b_two => 2, c_three => 3, d_four => 4, e_five => 5, f_six => 6, g_seven => 7, h_eight => 8, i_nine => 9, j_ten => 10 ); my $pairs = (keys %hash); my $counter = 0; my $amount_to_print = int(0.20 * $pairs); foreach my $key (reverse sort keys %hash) { if ($counter < $amount_to_print) { print $key, ' ', $hash{$key}, "\n"; } else { last; } $counter++; }

This will print:

j_ten 10 i_nine 9

Maybe there's some better solution?

Replies are listed 'Best First'.
Re^2: Selection of Hash key value pairs
by arkturuz (Curate) on Mar 31, 2006 at 10:31 UTC
    A little shorter:

    my @keys_to_print = (reverse sort keys %hash)[0 .. int(0.20 * (keys %h +ash))-1]; foreach my $key (@keys_to_print) { print_to_file($key, $hash{$key}); } sub print_to_file { # print to file }