my @sorted_matrix = grep {s/(^|\D)0+(\d)/$1$2/g,1} sort {$a->[0] cmp $b->[0]} grep {s/(\d+)/sprintf"%06.6d",$1/ge,1} @matrix;