#!/usr/bin/perl -w use strict; my @array = ([ "a", "b", "c", ], [ "1", "2", "3", "4", ], [ "x", "y", ], [ "U", "V", "W", "X", "Y", "Z",],); my (@current, @result); # In @current we store the array index to construct the string my $comb = 1; map($comb *= @{$_}, @array); # Get total permutations for (my $num = 1; $num <= $comb; $num++) { my $string = ''; for (my $k = 0; $k <= $#array; $k++) { $current[$k] = 0 if !$current[$k]; $string .= ${$array[$k]}[$current[$k]]; } if ($current[$#array] < $#{$array[$#array]}) { $current[$#array]++; } else #If we reach max index we increment previous not maxed one { $current[$#array] = 0; for (my $i = $#array-1; $i > -1; $i--) { # We exit the loop when we increment a not maxed index $current[$i] < $#{$array[$i]} ? do {$current[$i]++; last} : do {$current[$i] = 0}; } } push(@result, $string); } print join(",", @result) . "\n";