http://www.perlmonks.org?node_id=169231

Parham has asked for the wisdom of the Perl Monks concerning the following question:

i'll start off by saying, the only reason i redid the coding was to try and understand what was going on. I took the permutation subroutine from the perl cookbook and redid it without the use of passing arrays (i'm passing simple variables now, constructing and destructing them into arrays). I can better see how the program works now:
#!/usr/bin/perl use strict; permute("1 2 3 4",""); sub permute { my $old = @_[0]; my $new = @_[1]; my @old = split(/ /,$old); my @new = split(/ /,$new); print "old = @old | new = @new\n"; #helpful in seeing what's going o +n unless (@old) { print "@new\n"; } else { my $i; foreach $i (0..$#old) { my @new1 = @new; my @old1 = @old; unshift(@new1,splice(@old1,$i,1)); my $new1 = join(' ',@new1); my $old1 = join(' ',@old1); permute($old1,$new1); } } }
Fellow monks, i require your assistance in understanding this permutation program. The commented line shows what the function is doing while making the permutations:
old = 1 2 3 4 | new = 
old = 2 3 4 | new = 1
old = 3 4 | new = 2 1
old = 4 | new = 3 2 1
old =  | new = 4 3 2 1
4 3 2 1
old = 3 | new = 4 2 1
old =  | new = 3 4 2 1
3 4 2 1
old = 2 4 | new = 3 1
old = 4 | new = 2 3 1
old =  | new = 4 2 3 1
4 2 3 1
... too long to continue
i understand everything up to the first loop, but after that i start losing how the "old" array picks up info from the "new" array (seems to be working backwards?). I'm not having a perl problem, but rather a theory problem with how perl actually makes this work. If someone could give me a short step-by-step guide to what perl does with the array, i'd be most grateful. Rather than using the subroutine blindly, i'd like to get a little bit of information on how it's able to work. All help appreciated, and thanks in advance.