Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: Lookup closest hash keyby tilly (Archbishop) |
on Jan 25, 2011 at 07:19 UTC ( [id://884070]=note: print w/replies, xml ) | Need Help?? |
A hash is the wrong data structure to use. Instead you want an ordered data structure, like a BTree. If you want to know how one works internally, you can read BTrees in Perl. You don't need to roll your own. There is an excellent implementation called BerkeleyDB, which you can tie a hash to. It should be possible to do this using BerkeleyDB, with a custom sort operator and cursors. However I know it is possible to do this with the older DB_File. Read Matching Partial Keys which can look up the key and possibly get the next after. Then using the R_PREV flag with another seq should get you the previous key/value pair. And you can compare those two against the original to figure out which is closest. Note that BTrees default to lexicographic sort order, but you can pass a custom sort function. This is important if you need to avoid putting keys in the order 8, 89, 899, 9, 91, ...
In Section
Seekers of Perl Wisdom
|
|