I am wondering if there is an easier or more elegant way to delete all the keys in a hash except for n of them (say 5 of them)?
Example code would be:
Is it possible to do it without having to determine the number of keys in the hash first? Ordering of results or consistent results is not important, it just has to leave any n (say 5) from what was originally there. Have been thinking of using the array index -1 somehow, but no luck so far.my $n = 5; my %hash; @hash{ 0..20 } = 100..120; delete @hash{ (keys %hash)[$n..(scalar keys %hash)] };
Thanks for any insights into this!
In reply to Delete all hash keys except for n of them by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |