2

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 ?

Community
  • 1
  • 1
Tyzak
  • 2,430
  • 8
  • 38
  • 52

1 Answers1

4

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 ) ;
Zaid
  • 36,680
  • 16
  • 86
  • 155
  • hm some how it doesnt work exactly, the first value is missing, and the ' ' are missing and the first { does not appear :> – Tyzak Jan 05 '12 at 13:02
  • Ah, okay i get it... but my Array get the values from a textfile, and those are A-Z, a-z, 0-9 and "." "," "-" - i think this causes the error? – Tyzak Jan 05 '12 at 13:15