my @sorted_aoh = map $aoh[ substr $_, 5 ], sort map { # Retrieve the document number my $doc_key = (map /^doc(\d+)$/ ? 0 + $1 : (), keys %{$aoh[$_]})[0]; # Return the document number, a null and the original array index pack( 'N', $doc_key ) . "\0" . $_; } 0 .. $#aoh