Re: Arbitrarily Many Nested Loops




John W. Krahn wrote:
Jacob JKW wrote:
This is what I have:

-------------
#!perl

for (my $i = 0; $i<=$n_ra->[0]; $i++) {
for (my $j = 0; $j<=$n_ra->[1]; $j++) {
for (my $k = 0; $k<=$n_ra->[2]; $k++) {
$prob_ra->[$i+$j+$k] += (
$f_raa->[0]->[$i] *
$f_raa->[1]->[$j] *
$f_raa->[2]->[$k] *
);
}
}
-------------
But that's obviously messy and more imprtantly I'd like to be able to
decide at run time to have how nested levels to go (probably be on the
order of 50 or 60). I assume that there's a canonical manner in which
this should be handled (using closures I'd guess) but I can't
sufficiently summarize my issue to make it Google-able.

Easy enough to do in perl:

my $index_var = 'aa';
my @var_names = map '$' . $index_var++, 0 .. $#$n_ra;

my $nested_loop = join( '',
map "\t" x $_
. 'for ( my '
. $var_names[ $_ ]
. ' = 0; '
. $var_names[ $_ ]
. ' <= $n_ra->[ '
. $_
. ' ]; '
. $var_names[ $_ ]
. "++ ) {\n", 0 .. $#$n_ra )
. "\t" x $#$n_ra
. '$prob_ra->[ '
. join( ' + ', @var_names )
. " ] +=\n"
. join( " *\n",
map "\t" x @$n_ra
. '$f_raa->[ '
. $_
. ' ]->[ '
. $var_names[ $_ ]
. ' ]', 0 .. $#$n_ra )
. "\n"
. join '', map "\t" x $_ . "}\n", reverse 0 .. $#$n_ra;

eval $nested_loop;
You know, I initially shied away from this method just because I've
always had a problem with the brute force ugliness of eval. But the
truth is that even if not the prettiest, this is simply the fastest and
most direct way to go.

Highly appreciate the advice and the ready to go out the box code. :-)

.



Relevant Pages

  • Re: Perl style examples (summary)
    ... For CGI: http://users.easystreet.com/ovid/cgi_course/ (John W. Krahn) ... "Perl Best Practices" by Damian Conway ... Janet Goldstein, Christian Winter, Adrian Howard. ...
    (comp.lang.perl.moderated)
  • Re: Passing command line arguments
    ... On Friday 15 April 2005 12:18 am, John W. Krahn wrote: ... >> You could paste the two arguments together in perl, ... Prev by Date: ...
    (perl.beginners)
  • Re: How to deal with binary file?
    ... Tony Winslow wrote: ... John W. Krahn wrote: ... Perl is binary clean, so this shouldn't be a problem. ...
    (comp.unix.shell)
  • Re: Extracting Date using Regular Expressions
    ... John W. Krahn wrote: ... I need some help in regular expressions.... ... Perl isn't a toolbox, but a small machine shop where you can special-order ...
    (comp.lang.perl.misc)
  • Re: How do I create this string?
    ... Flemming Greve Skovengaard wrote: ... John W. Krahn wrote: ... makes no sense so perl converts the value of the index to an integer so the ...
    (perl.beginners)