in reply to retrieve next avaiable element in sorted hash

vinforget,
It seems to me that what makes this problem difficult to solve without a loop is that you want the next key after a specified key that is defined. I do not know how much more efficient the following logic would be then a loop. I imagine it depends on the size of the hash and the location of the key.

  • If the desired key does not exist, return undef
  • If the desired key is defined, return the value
  • If not, create an array of sorted hash keys that are defined + target key
    my @keys = grep { defined $hash{$_} || $_ eq $key } sort keys %hash;
  • Use a binary search to find the index of the target key and return the array element one higher
  • It is your choice if it should loop around to the first key if it is the last element or return undef

    I am too tired at the moment (just started a new job) to actually write this code, but the binary search should be noticeably faster on large hashes especially if the target key is not at the beginning. If you are interested I will update it later.

    Cheers - L~R