The smallest fix is to simply move the 'my' to be inside the loop:

for my $i (1..$depth-1) { my $val = 1 + 2*$i; push @$loop, sub {[$_+1..$val]}; }

or, even

my $val= 3; for my $i ( 1 .. $depth-1 ) { my $end= $val; push @$loop, sub {[$_+1..$end]}; $val += 2; }

and the reason this makes a difference is that your code uses a single instance of the $val variable and all of the closures you make share it. When the closures finally get run [several times each, during the call to NestedLoops()] is when the value of $val is used. $val doesn't stay 3 so your loops don't stop at 3.

You can build the list in-line, for example:

#!/usr/bin/perl -w use strict; use Algorithm::Loops 'NestedLoops'; my $depth= 4; my $iter= NestedLoops( [ [0..1], map { my $end= 2*$_+1; sub { [$_+1..$end] } } 1..$depth-1, ], ); while( my @list= $iter->() ) { output(@list); } sub output { print join '', @_, "\n"; }

- tye        


In reply to Re: Building the loop arrayref for Algorithm::Loops::NestedLoops (stays shared) by tye
in thread Building the loop arrayref for Algorithm::Loops::NestedLoops by Zed_Lopez

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.