Reputation: 2438
I just read
How can I generate all permutations of an array in Perl? http://www.perlmonks.org/?node_id=503904 and https://metacpan.org/module/Algorithm::Permute
I want to create all possible combinations with a userdefined length of values in an array.
perlmonks did it like this:
@a= glob "{a,b,c,d,e,1,2,3,4,5}"x 2;
for(@a){print "$_ "}
and this works fine, but instead of "{a,b,c,d,e,1,2,3,4,5}"
I would like to use an array
i tried this:
@a= glob @my_array x $userinput ;
for(@a){print "$_ "}
but it didn't work, how can I do that? Or how can I limit the length of permutation within Algorithm::Permute ?
Upvotes: 2
Views: 631
Reputation: 37136
Simply generate the string from the array:
my @array = ( 'a' .. 'e', 1 .. 5 );
my $stringified = join ',', @array;
my @a = glob "{$stringified}" x 2;
say 0+@a; # Prints '100';
say join ', ', @a; # 'aa, ab, ac, ad ... 53, 54, 55'
One could also use a CPAN module. Like List::Gen
:
use List::Gen 'cartesian';
my @permutations = cartesian { join '', @_ } map [ $_ ], ( 'a'..'e', 1..5 ) ;
Upvotes: 4