use Tie::Hash::Sorted; my $custom_sort = sub { my $hash = shift; [ sort { $hash->{$b}{pkts} <=> $hash->{$a}{pkts} || $hash->{$b}{size} <=> $hash->{$a}{size} } keys %$hash ]; }; tie my %flows, 'Tie::Hash::Sorted', 'Sort_Routine' => $custom_sort, 'Optimization' => 'none' ; for ( keys %flows ) { # Will always be sorted the way you want }