http://qs321.pair.com?node_id=402175


in reply to Delete all hash keys except for n of them

One nice way to do this is to treat the hash as array, then take a slice from the array and reassign it. The program below demos this approach.
#!/usr/bin/perl use strict; use warnings; # Create a test hash. my %test; $test{$_}="$_-$_" for ('aa' .. 'zz'); # Grab N keys. my $num_keys = 5; %test = (%test)[0..$num_keys*2-1]; # Display the result for (sort keys %test) { print "$_ = $test{$_}\n"; }