Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Lookup closest hash key

by tilly (Archbishop)
on Jan 25, 2011 at 07:19 UTC ( #884070=note: print w/replies, xml ) Need Help??


in reply to Lookup closest hash key

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, ...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://884070]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2021-01-24 00:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?