# Thanks to aristotle for making the regex simpler my $string = "abcd"; my @perms; my $regex = qr/(\G[abcd]{0,4}(?{print "# [$&][$'][$string]\n"}))/ x 2; $string =~ $regex;