Forum Moderators: coopster & phranque

Message Too Old, No Replies

Perl Loop

         

lindajames

1:48 pm on May 19, 2003 (gmt 0)

10+ Year Member



Hi,

Can anyone tell me where the loop ends on the following code:

for (;$n > 0 ; $n--) {

if ($isfirst) { bodyprint("Manage\n\n"); $isfirst = 0; }

bodyprint("&raquo; $s<br>\n");
}
bodyprint("</center>\n\n");

Any suggestions would be appreciated.

Cheers
Linda

BCMG_Scott

3:08 pm on May 20, 2003 (gmt 0)

10+ Year Member



Indentation often helps:

for (;$n > 0 ; $n--) {
__if ($isfirst) { bodyprint("Manage\n\n"); $isfirst = 0; }
__bodyprint("&raquo; $s<br>\n");
}
bodyprint("</center>\n\n");

Now can you see where it ends?

Scott Geiger

(I used underscores to indent, don't copy them or your code will break)

lrovi

10:11 pm on May 22, 2003 (gmt 0)



With where it ends answered above (via Scott's reply); when it'll end is when $n fails to be greate than zero.

ShawnR

10:33 am on May 23, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Linda

Are you just maintaining the code, or did you write it? If you wrote it, I'd suggest you change it slightly as I think it is not great style. People learn to read (including reading code) by recognising patterns. A programer with even a small amount of experience will quickly speed-read something like the following, because it is a commonly used pattern:

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

but may have to look twice to figure out your loop, which is exactly equivalent.

The only disadvantage is introducing the additional variable. But despite perl not being a compiled language, I think perl is smart enough for this not have any effect on performance. If you really wish to avoid introducing the additional variable, then another alternative is:

while ($n--) {...}

So I'd suggest something like:


if ($n) {
____bodyprint("Manage\n\n");
}
while ($n--) {
____bodyprint("&raquo; $s<br>\n");
}
bodyprint("</center>\n\n");

Shawn