my @flat = sort { $a <=> $b } map @$_, @orig; my @sorted = map [ $orig[3*$_ .. 3*$_+2] ], 0 .. $#flat/3;