I need to use function cartesian from List::Gen. This function requires LIST as a second parameter, but I have an array, like
$VAR1 = [
[
1,
2,
3
],
[
'a',
'b',
'c'
],
[
'x'
]
];
How can I "convert" such array into list, so cartesian can be used? Putting array into list context does not seems to work in this case.
2 Answers 2
Parens don't create lists, they just change precedence.
@a = ((1, 2, 3), (7, 8, 9));
is the same as
@a = (1, 2, 3, 7, 8, 9);
The examples of cartesian show a list of references to arrays
cartesian { $_[0] . $_[1] } [1,2,3], [7,8,9];
So it seems you want to create an array containing two elements, each a reference to another array.
@a = ( [1,2,3], [7,8,9] );
Then, to answer your question, evaluating @a in list context will return these two references.
cartesian { $_[0] . $_[1] } @a;
3 Comments
@a = ((1, 2, 3), (7, 8, 9)) is not an array of arrays. It's just an array. use Data::Dumper; print Dumper \@a; to see for yourself.Data::Dump or an equivalent to dump the contents of the array you want to pass to cartesian. If you publish the results here then we will be able to help you better.In your new question, you have
$VAR1 = [
[
1,
2,
3
],
[
'a',
'b',
'c'
],
[
'x'
]
];
Despite your claims that it doesn't work, all you need is to evaluate the array in list context.
cartesian { ... } @$VAR1;
For example,
( cartesian { join '|', @_ } @$VAR1 )->say;
gives
1|a|x 1|b|x 1|c|x 2|a|x 2|b|x 2|c|x 3|a|x 3|b|x 3|c|x
push. Then the argument needs to be an array. There is no reversed incompatibility: A LIST can always be an array, but ARRAY cannot always be a list.use Data::Dumper; print Dumper \@a;my @b = Set::CrossProduct->new([@a])->combinations;