in reply to Please help me understand this permutation sub?
use strict; use warnings; sub permutation { my ($perm,@set) = @_; unless(@set) { print "$perm\n" || die("Print error:$!"); } else { permutation($perm.$set[$_], (@set[0..$_-1],@set[$_+1..$#set]) ) foreach (0..$#set); } return; } my @input = (qw/a b c d/); permutation('',@input);
UPDATE: I now believe that you original code had a serious error and it was only by pure luck that it worked at all. The '||' operator before the 'return' should be an 'and' operator. With this change, function appears to work exactly the same. The difference is that now, the 'return' is executed immediately after every print. The behavior of 'foreach' in this special case is no longer an issue. Note that the lower priority operator 'and' instead of '&&' is needed to make the string bind to the print rather than the '&&'. The reverse logic is needed because print returns a true value on success. I have never seen a failure.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Please help me understand this permutation sub?
by mdunnbass (Monk) on Dec 09, 2020 at 14:09 UTC |