I'm trying to use Algorithm::Loops::NestedLoops to dynamically create a set of loops (of depth to be determined at runtime) like this:

for $i (0..1) { for $j ($i+1..3) { for $k ($j+1..5) { for $l ($k+1..7) {

and so on. NestedLoops makes the $i+1 part easy, but I don't know how to generate the anonymous subroutines such that they'll have the right values for the ends of the ranges.

The obvious approach

my $depth = 4; my $loop = [[0..1]]; my $val = 3; for my $i (1..$depth-1) { push @$loop, sub {[$_+1..$val]}; $val+=2; } my $iter = NestedLoops($loop); while (my @list = $iter->()) { output(@list); } sub output { my @args = @_; print join '', @args, "\n"; }

fails because $val isn't evaluated when the subroutine is defined; it's evaluated when it's run, such that they all get its last value, 9.

Trying to be more clever by using an iterator:

my $n = shift; sub plustwo_iter { my $val = 1; return sub { $val +=2; return $val; } } my $p = plustwo_iter(); my $loop = [[0..1], (sub {[$_+1..&$p]}) x ($n-2)]; my $iter = NestedLoops($loop); while (my @list = $iter->()) { output(@list); }

fails because NestedLoops seems to end up calling the iterator more than exactly once per loop (not that I'd want to depend on the assumption it did call it exactly once per loop.)

Does anyone see how this can be done with NestedLoops? (I have another solution where I build code and eval it, but I'd like to try it with NestedLoops, too.)


In reply to 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.