sub NestedLoops { my( $loops, $when )= @_; my @list; my $i= -1; my @idx; my @vals= @$loops; my %freq; return sub { return } if ! @vals; return sub { while( 1 ) { # Prepare to append one more value: if( $i < $#$loops ) { $idx[++$i]= -1; local( $_ )= $list[-1]; $vals[$i]= $loops->[$i]->( @list ); } ## return if $i < 0; my $act = -1; while( $act < 0 ) { # Increment furthest value, chopping if done there: while( @{$vals[$i]} <= ++$idx[$i] ) { --$freq{ $list[$i] }; pop @list; return if --$i < 0; } $act = do { --$freq{ $list[$i] } if 0 < $idx[$i]; local $_ = ++$freq{ $list[$i]= $vals[$i][$idx[$i]] }; $when->( @list ); }; return @list if 0 < $act; } } }; }