Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I wondered if anyone had some neat tricks to save me typing out similar loops 100 times?!? The first part of the code is below - it is a basic incrementation of $i and then incrementing the number that $i is being compared to each time - up until about 100. The code does work as i wish, but it will take up too much room. Thanks a lot!
for (my $i = 0; $i < @existing_wells; $i++) { if ($existing_wells[$i] == 1) { print qq(<area href="http://cgi-bin/$graph_links[0 +]" ALT="" shape="circle" coords="13,9,6">); } else { print qq(<area href="http://cgi-bin/array.bmp" ALT +="" shape="circle" coords="13,9,6">); } if ($existing_wells[$i+1] == 2) { print qq(<area href="http://cgi-bin/$graph_links[1 +]" ALT="" shape="circle" coords="184,9,6">); } else { print qq(<area href="http://cgi-bin/array.bmp" ALT +="" shape="circle" coords="184,9,6">); } }

Replies are listed 'Best First'.
Re: minimising repetitive if-elsing
by zby (Vicar) on May 29, 2003 at 14:30 UTC
    Loop in loop? Something like:
    for my $i (0 .. $#existing_wells){ for my $j (0 .. 100){ # or perhaps (0 .. min(100, $#existing_wells - $i) if($existing_wells[$i + $j] == $j + 1){ print qq( ...
    I prefere this type of looping over lists. You need to have an expression for the coordinates too.
Re: minimising repetitive if-elsing
by TomDLux (Vicar) on May 29, 2003 at 14:47 UTC

    For the hundred goals, you display 'array.bmp' if the match fails and an image specified by a name in an array if the match succeeds. Setting the appropriate value into a local variable allows a single print statement.

    For each of the hundred goals, you have a different set of coords. Set up an array with the values stored in inner arrays, and then format the appropriate set into a variable for the print statement. If you can have an undef or empty first element in @graph_links then you could use $goal instead of $goal-1 in that line as well.

    Sample code follows ...

    But if you have a 50 elements in @existing_wells you wind up with 5000 lines of output of about 75 characters each, or about 375,000 characters just for this section. Is there a different way of dealing with this?

Re: minimising repetitive if-elsing
by hardburn (Abbot) on May 29, 2003 at 14:15 UTC

    It depends on what changes for each run through the loop. If the "coords" param in your HTML stays the same for each respective postion, you could move its parameter into a second array, indexed by "$i + $some_num", where $some_num is what you're incrementing $i by in your if statement.

    There really isn't enough information in your post to help you further.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated