perlfaq nodetype
faq_monk
<P>
Here's a little program that generates all permutations of all the words on each line of input. The algorithm embodied in the
<CODE>permute()</CODE> function should work on any list:
<P>
<PRE> #!/usr/bin/perl -n
# tsc-permute: permute each word of input
permute([split], []);
sub permute {
my @items = @{ $_[0] };
my @perms = @{ $_[1] };
unless (@items) {
print "@perms\n";
} else {
my(@newitems,@newperms,$i);
foreach $i (0 .. $#items) {
@newitems = @items;
@newperms = @perms;
unshift(@newperms, splice(@newitems, $i, 1));
permute([@newitems], [@newperms]);
}
}
}
</PRE>
<P>