Nothing is jumping out at me from CPAN, except maybe Tie::RangeHash, which you might find a way to use with what you're doing. If not, here's a solution (not particularly efficient though):

sub get_fuzzy { my ($k, $h) = @_; return $h->{$k} if exists $h->{$k}; for (sort keys %$h) { return $h->{$_} if $_ gt $k; # if keys are numeric, change "g +t" to ">" } return undef; # if key is higher than the highest } my %hash = (a=>1, c=>3, e=>5, g=>7, i=>9); print "|", join('|', map { get_fuzzy($_, \%h) } a..j), "|\n";

It's inefficient because it sorts all the hash keys each time there is a lookup and does a linear search through them. Also, I'm not sure what you want to do when looking up a value larger than the largest hash key. In this case, my code returns undef.

If you want efficiency, you may want to tie a class of your own that maintains the keys in sorted order, perhaps even indexed so you could do a binary search instead of a linear one.

-- Mike

--
XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
-- grantm, perldoc XML::Simpler


In reply to Re: retrieve next avaiable element in sorted hash by thelenm
in thread retrieve next avaiable element in sorted hash by vinforget

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.