in reply to List of Numbers
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.#!/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"; }
(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.)
|
|---|