baxy77bax has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

this is probably simple but i need some help with it anyway. So i have a nested loop like this:

for (my $i = 1; $i<=6; $i++){ for (my $ii = 1; $ii<=6; $ii++){ for (my $iii = 1; $iii<=6; $iii++){ for (my $iiii = 1; $iiii<=6; $iiii++){ for(my $j=1;$j<=6;$j++){ for(my $jj=1;$jj<=6;$jj++){ for(my $jjj=1;$jjj<=6;$jjj++){ print "$i,$ii,$iii,$iiii,$j,$jj,$jjj\n"; } } } } } } }
(at some point i switched from $iiii to $j because it is easier to type)
what i need is to do this dynamically, that is, i would like to specify the number of loops i need, let say 10 and then i get 10 for loops executed as in the above example.

so instead of writing 10 for loops i would need to do this dynamically.

baxy

Replies are listed 'Best First'.
Re: nested loops
by BrowserUk (Patriarch) on Jan 09, 2014 at 16:33 UTC

    sub nForX(&@) { my $code = shift; my $n = shift; return $code->( @_ ) unless $n; for my $i ( @{ shift() } ) { &nForX( $code, $n-1, @_, $i ); } } nForX{ print "@_"; } 6, ([1..6]) x 6;; 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 3 1 1 1 1 1 4 1 1 1 1 1 5 1 1 1 1 1 6 1 1 1 1 2 1 1 1 1 1 2 2 1 1 1 1 2 3 1 1 1 1 2 4 1 1 1 1 2 5 ...

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
    .
Re: nested loops
by hdb (Monsignor) on Jan 09, 2014 at 16:27 UTC
Re: nested loops
by Anonymous Monk on Jan 09, 2014 at 16:28 UTC