http://www.perlmonks.org?node_id=250938


in reply to Creating tuples based on sets

#!perl -w use strict; my @set = qw(a b c); my @tuples = mk_tuples(3, \@set); for (@tuples) { print "(", join(", ", @$_), ")\n"; } sub mk_tuples { my $n = shift; my $setr = shift; my $len = 0; my @result = (); my @hold = (); mk_tuples_r($n, $setr, \@hold, \@result); return @result; } sub mk_tuples_r { my ($n, $setr, $holdr, $resultr) = @_; my $len = 1 + @$holdr; for my $e (@$setr) { push @$holdr, $e; if ($len == $n) { push @$resultr, [ @$holdr ]; } else { mk_tuples_r($n, $setr, $holdr, $resultr); } pop @$holdr; } }