use Algorithm::Loops qw( NestedLoops ); for my $depth (2..3) { NestedLoops( [ ([ 0..3 ]) x $depth ], sub { print(join(', ', @_), "\n"); }, ); }