Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

How to create loop in perl dynamically

by adithi (Initiate)
on Sep 26, 2012 at 13:11 UTC ( #995764=perlquestion: print w/replies, xml ) Need Help??
adithi has asked for the wisdom of the Perl Monks concerning the following question:

I have one input parameter, based on that i want to create for loop those many times. How do i achieve this?
$input=2 for($i=0;$i<2;$i++) { for($j=0;$j<18;$j++) {} }
Here, $input=2.
If $input=3, i want 3 for loops. Please help me out in this.

Replies are listed 'Best First'.
Re: How to create loop in perl dynamically
by roboticus (Chancellor) on Sep 26, 2012 at 13:15 UTC


    for ($i=0; $i<$input; $i++) { ... }


    When your only tool is a hammer, all problems look like your thumb.

Re: How to create loop in perl dynamically
by grizzley (Chaplain) on Sep 26, 2012 at 13:25 UTC
    I would create array containing max values for each loop and iterate over array.
    #!perl -l @maxvalues = (2, 5, 3); $input = 3; my @ids = (0) x $input; # assuming all loops start with 0 while(!$end) { # do something print "[@ids]"; # increase values starting from end of ids array $index = $#ids; while(1) { $ids[$index]++; if($ids[$index]<=$maxvalues[$index]) { last } else { # we reached limit on loop pointed by $index $ids[$index] = 0; $index--; if($index<0) # check stop condition { $end = 1 } } } }
      Thank u. But I didnt the logic used here.
        Then spend some time analyzing it, understanding the code you want to use is very important. If you won't get it (actually even if you will) - use module, as advised here: Re: How to create loop in perl dynamically
Re: How to create loop in perl dynamically
by djerius (Beadle) on Sep 26, 2012 at 13:38 UTC
    Since your loops are nested, you're really generating a cartesian product of the list indices; try Math::Cartesian::Product.
      Not sure how to do this. But will try this.
        Your problem requires the following
        • The number of loops
        • The iteration ranges for each loop
        • Code which uses the loop indices
        You can encode the first two however you'd like; in the following example I've simply put the ranges in an array.

        You haven't provided an example of the code which runs inside the innermost loop. It might be useful if you provided some idea of what you're trying to do inside of those loops.

        I'm assuming that your code only needs to know the loop indices.

        Here's how you can use Math::Cartesian::Product:

        use Math::Cartesian::Product; # this encodes the number of loops and their ranges my @ranges = ( [ 0..1 ], [ 1..2 ], [2..3] ); # the code inside the braces is run for every combination # of the ranges cartesian { print "indices: @_\n"; } @ranges; # here's a version using a subroutine which sums up # the indices (just to do something with them) sub compute { my $sum = 0; $sum += $_ foreach @_; print "sum of @_ = $sum\n"; } cartesian \&compute, @ranges;
        And here are the results:
        indices: 0 1 2 indices: 0 1 3 indices: 0 2 2 indices: 0 2 3 indices: 1 1 2 indices: 1 1 3 indices: 1 2 2 indices: 1 2 3 sum of 0 1 2 = 3 sum of 0 1 3 = 4 sum of 0 2 2 = 4 sum of 0 2 3 = 5 sum of 1 1 2 = 4 sum of 1 1 3 = 5 sum of 1 2 2 = 5 sum of 1 2 3 = 6
Re: How to create loop in perl dynamically
by Anonymous Monk on Sep 26, 2012 at 13:56 UTC

    Also, from perldoc perlop:

    Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty list. The range operator is useful for writing "foreach (1..10)" loops and for doing slice operations on arrays. In the current implementation, no temporary array is created when the range operator is used as the expression in "foreach" loops, but older versions of Perl might burn a lot of memory when you write something like this:
    for (1 .. 1_000_000) { # code }

      Will try range operator. Thank u.
        I tried this, $index is input
        Here if $index =2, foreach gets created 2 times, But how do i code inside this and control loop parameters.
        Please suggest

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://995764]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2017-01-20 21:41 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (177 votes). Check out past polls.