in reply to How do I keep the first key in a sorted hash?

Ah, nevermind, I just thought of passing the keys to an array and then sort the array:
@sorted_positions = sort { $a <=> $b };
Then, I get the $sorted_positions[0] element and everything is OK!

Replies are listed 'Best First'.
Re^2: How do I keep the first key in a sorted hash?
by Not_a_Number (Prior) on Feb 17, 2014 at 12:18 UTC

    You can even do away with the intermediate array variable:

    my $min = ( sort { $a <=> $b } keys %hash )[ 0 ];
Re^2: How do I keep the first key in a sorted hash?
by Laurent_R (Canon) on Feb 17, 2014 at 18:42 UTC
    If your hash is large, then using the sort function just to retrieve the smallest value is inefficient overkill. Use a variable, say $min, and set it to any key that you know to exist (or to a very large value such as 1e10 that you know will larger than at least one of the keys). Then you can simply do something like this:
    my $min = 1e10; for my $key (keys %h) { $min = $key if $key < $min; } # now, $min is the smallest key. The associated value is simply $h{$mi +n}
    Now, depending on how you get the data in the first place, you could also maintain the $min variable when populating the hash, thereby avoiding to read all the keys once more.