mdunnbass has asked for the wisdom of the Perl Monks concerning the following question:
Greetings esteemed Monks,
Forgive me for I have sinned, it has been...... ~13 years since my last seeking of wisdom.
I'm trying to write myself a little script to read in a file of multiple choice questions, permute their A-D answers, and write it all back out to files. SO far, everything is under control and going well except the actual permuting part of it all. I've found a handful of discussions on how to do this in perl, here and elsewhere, and I'm not so much asking how to do it. I found a lovely little recursive sub on RosettaCode that works beautifully. But I would like to know how 1 aspect of the code is functioning.
So, the sub in question is:
sub permutation { my ($perm,@set) = @_; print "$perm\n" || return unless (@set); permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreac +h (0..$#set); } my @input = (qw/a b c d/); permutation('',@input);
I've thrown all kinds of say statements in to track each aspect of the code as it runs, and I can't figure out how it initiates a second permutation.
The first permutation arises from essentially shifting the first element of @set and catenating it onto $permute, one element at a time. OK, great, I get that, it's pretty straightforward. But then, what gets me is the following:
After the first permutation has completed, $perm = '1234' and @set is empty. Dumper tells me that $_ has been = 0 since it was initialized. When the code reaches this line at this point:
permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreach (0 +..$#set);
$perm is now equal to '124,' @set = 3, and $_ = 1.
How did that recursive call to the permutation pull 3 out of the string and put it in set? The closest thing to a coherent idea I could come up with was that maybe $set[$_]is now undefined, so catenating that to permute actually acted like catenating a -1 and popped the -1 element out of it? But if that's the case, how did that get added into @set?
Or do I have it all wrong? Am I looking in the wrong place?
Any insights would be greatly appreciated.
Thanks.
mdunnbass
|
|---|