my $hash = { foo => { one => [ 1 .. 3 ], }, bar => { two => [ 1 .. 6 ], }, baz => { three => [ 1 .. 9 ], }, }; my @sorted; foreach my $s (keys %$hash) { push @sorted, map [ scalar @{$hash->{$s}{$_}}, $s, $_ ], keys %{ $hash->{$s} }; } print join(" ", @$_), $/ for sort { $a->[0] <=> $b->[0] } @sorted; __output__ 3 foo one 6 bar two 9 baz three