foreach my $key (sort hashKeyLengthAsc (keys(%count))) [...] } sub hashKeyLengthAsc { length($a) <=> length($b) }