perlcartesian-productcross-productlist-manipulation

In Perl, how can I get the Cartesian product of multiple sets?


I want to do permutation in Perl. For example I have three arrays: ["big", "tiny", "small"] and then I have ["red", "yellow", "green"] and also ["apple", "pear", "banana"].

How do I get:

["big", "red", "apple"]
["big", "red", "pear"]

..etc..

["small", "green", "banana"]

I understand this is called permutation. But I am not sure how to do it. Also I don't know how many arrays I can have. There may be three or four, so I don't want to do nested loop.


Solution

  • That's actually not permutation but Cartesian product. See Math::Cartesian::Product.

    #!/usr/bin/perl
    
    use strict; use warnings;
    
    use Math::Cartesian::Product;
    
    cartesian { print "@_\n" }
        ["big", "tiny", "small"],
        ["red", "yellow", "green"],
        ["apple", "pear", "banana"];
    

    Output:

    C:\Temp> uu
    big red apple
    big red pear
    big red banana
    big yellow apple
    big yellow pear
    big yellow banana
    big green apple
    big green pear
    big green banana
    tiny red apple
    tiny red pear
    tiny red banana
    tiny yellow apple
    tiny yellow pear
    tiny yellow banana
    tiny green apple
    tiny green pear
    tiny green banana
    small red apple
    small red pear
    small red banana
    small yellow apple
    small yellow pear
    small yellow banana
    small green apple
    small green pear
    small green banana