# Hash sort

Suppose I have a hash of this type:

``my %hash = ('Андрей' => 3, 'Вася' => 2, 'Петя' => 5, 'Коля' => 2, 'Женя' => 4);` `

And I need to deduce elements with the minimum value from it. That is, the result should be

Vasya 2

Kolya 2

Actually, how can this be implemented more rationally?

If you sort the values ​​and then select the minimum:

` `my \$min; for my \$name (sort { \$hash{\$a} <=> \$hash{\$b} } keys %hash) { my \$value = \$hash{\$name}; last if defined(\$min) && \$min != \$value; \$min = \$value; print "\$name \$value\n"; }` `

If not sort:

` `use List::Util qw(min); my \$min = min values %hash; while(my (\$name, \$value) = each %hash) { print "\$name \$value\n" if \$value == \$min; }` `

If you sort the names:

` `use List::Util qw(min); my \$min = min values %hash; for my \$name (sort grep { \$hash{\$_} == \$min } keys %hash) { print "\$name \$min\n"; }` `

not correct, cmp sorts the strings, and here the numbers. You must use the comparison operator (<=>):

` `my \$min; foreach my \$key (sort { (\$hash{\$a} <=> \$hash{\$b}) || (\$a cmp \$b) } keys %hash) { if (!defined \$min) { \$min = \$hash{\$key}; } elsif (\$hash{\$key} != \$min) { last; } print "\$key \$hash{\$key}\n"; }` `
• Yes, corrected the operator, thanks. - drdaeman