Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Delete all hash keys except for n of them

by Molt (Chaplain)
on Oct 25, 2004 at 09:18 UTC ( #402175=note: print w/replies, xml ) Need Help??


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"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://402175]
help
Chatterbox?
[Discipulus]: if i can suggest La Reine Margot too is a great book and obviously The Count of Monte Cristo that is a chef-d'œuvre
[Discipulus]: The red sphinx is about Rechilieu, absolutely thrilling
[erix]: thanks, Discipulus - I got them lined up at gutenberg :)
[erix]: I red the musketeers and Monte Cristo but both a very long time ago (many decades ago)
[erix]: *read
[Discipulus]: dunno if a young people can well understand the deep of Montecristo

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2017-05-24 07:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?