in reply to Iterating over an array variable times

One possible way would be to do a routine that calculates the next state from the previous one no matter how many 'N's are in the array. That way you just put the number of 'N's at the beginning of the array and call the routine repeatedly until all 'N's are at the end of the array

use warnings; use strict; my @arr=qw/A B C D E F/; my $anzahl=2; unshift @arr, ('N') x $anzahl; print join (",",@arr),"\n"; while (@arr= step (@arr)) { print join (",",@arr),"\n"; } sub step { # returns empty list if all marks are already at the end my @arr= @_; my $marksatend=0; my $i= @arr; #count marks at the end while ($i) { if ($arr[--$i] eq 'N') { $marksatend++; } else { last; } } #find a mark to advance my $mark=-1; while ($i) { if ($arr[--$i] eq 'N') { $mark=$i; last; } } #advance if ($mark<0) { return (); } else { my $tmp= $arr[$mark]; $arr[$mark]= $arr[$mark+1]; $arr[$mark+1]= $tmp; if ($marksatend>0) { splice @arr,-$marksatend; splice @arr,$mark+2,0, ('N')x$marksatend; } return @arr; } }