Search code examples
perlfactorization

how to factorize two lists


is there a way to factorize some lists easily in perl?

For example with 2 lists ('a', 'b', 'c') and ('d', 'e', 'f') I want the output ('ad', 'ae', 'af' .... 'ce', 'cf')

for now i'm doing

use strict;
use warnings;

my @listA = ('a', 'b', 'c');
my @listB = ('d', 'e', 'f');
my @listC = ();

foreach my $elementA (@listA)
{
    foreach my $elementB (@listB)
    {
        push(@listC, $elementA.$elementB);
    }
}

This works fine, but I would like to know if there is a more "perlish" way to do so?

thanks :)


Solution

  • Solution for arbitrary number of lists:

    use Algorithm::Loops qw( NestedLoops );
    
    my @arrays = (
       [qw( a b c )],
       [qw( d e f )],
       ...
    );
    
    my @result;
    NestedLoops(\@arrays, sub { push @result, join("", @_); });
    

    or

    my @result;
    my $iter = NestedLoops(\@arrays);
    while (my @comb = $iter->()) {
       push @result, join("", @comb);
    }