my $length = 5; my $str = "0" x $length; my $start = $str . "1"; do { print "$str\n"; } while ($str =~ s/^(1*0)/substr $start, -length $1/e)