blokhead's code suffers greatly in terms of performance, when the hash is big.
On my old PC, tachyon's code only took 2 seconds to run with a hash with 100_001 elements. My following version has the same performance as tachyon's, as you can see the idea is the same, instead of deleting, we simply form a new hash: (To test other solutions, simply plug them in between those two print time)
use Data::Dumper; my $n = 5; my %hash; @hash{ 0..100_000 } = 0..100_000; print time, "\n"; my %temp; @temp{(keys(%hash))[0..4]} = (values(%hash))[0..4]; %hash = %temp; print time, "\n"; print Dumper(\%hash);
Update:
When I was writing thhis post, both davido and TedPride's code were not there... I retested all solutions above on my new PC, all solutions other than blokhead's took 0 second to complete (< 1 second). blokhead's took 30 seconds.
OP's code took 0 second, but has a warning: "Use of uninitialized value in delete at b.pl line 7."
In reply to Re: Delete all hash keys except for n of them
by pg
in thread Delete all hash keys except for n of them
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |