Here's a solution structured as a subroutine; the "main" portion just uses your example data, and when run at the command line, it uses the first argument after the script name as the value of "$x":
#!/usr/bin/perl $num{'15'}=1; $num{'20'}=2; $num{'25'}=3; $num{'30'}=4; $x=shift; # take value from @ARGV print value_sought( $x ), $/; sub value_sought { my $x = shift; # take value from @_ foreach my $k ( sort { $a <=> $b } keys %num ) { return $num{$k} if ( $x < $k ); } return "$x is larger than available num keys"; }
But, as Abigail suggested in an earlier reply, if you're doing frequent searches over a large set of hash keys, you may want to optimize this a bit -- sort the keys into an array, check the value of $x against the middle element of that array, then the middle of the upper half or lower half as appropriate, until you hone in on the right key value; in the majority of cases, the correct element will be found in fewer iterations this way.

(If the set of hash keys is fairly static -- you do a lot of searches over the same set of hash keys -- then having the array will also help by not having to sort the hash keys every time you do a search.)


In reply to Re: List of Numbers by graff
in thread List of Numbers by Anonymous Monk

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.