$rindex = 0; $i = 1; do { foreach ( @columns ) { if ( $_ <= $qstart_column - 2 ) { $unsorted[$rindex][$_] = $x[$i][$_]; } else { $unsorted[$rindex][$_] = $x[$i][$_ - $nun_of_questions]; } } $rindex += 1; $i += $nun_of_questions; } while ( $i <= $#x );