<%@ LANGUAGE = PerlScript%> Testing loops in PerlScript at different conditions
ActiveState PerlScript

Repeating a Loop While a Condition Is True

Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example).

<% #First example of the While keyword $MyNum = 20; $Counter = 0; while ($MyNum >10) { $MyNum--; $Counter++; }; %> The first loop made <%= $Counter %> repetitions.

<% $Counter = 0; $MyNum = 9; $Counter++; $MyNum--; while ($MyNum > 10) { $MyNum--; $Counter++; }; %> The second loop made <%= $Counter %> repetitions.

Repeating a Statement Until a Condition Becomes True

You can use the Until keyword in two ways to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example). As long as the condition is False, the looping occurs.

<% #First example of the Until keyword $Counter = 0; $MyNum = 20; while ($MyNum != 10) { $MyNum--; $Counter++; }; %> The first loop made <%= $Counter %> repetitions.

<% # Second example of the Until keyword $Counter = 0; $MyNum = 1; while ($MyNum!=10) { $MyNum++; $Counter++; }; %> The second loop made <%= $Counter %> repetitions.

Exiting a Do ... Loop Statement from Inside the Loop

You can exit a Do ... Loop by using the Exit Do statement. You usually want to exit when you have accomplished the task the loop is performing or in certain situations to avoid an endless loop.

In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.

<% $Counter = 0; $MyNum = 9; while ($MyNum != 10) { $MyNum--; $Counter++; if ($MyNum < 10) { $MyNum=10; } }; %> The loop made <%= $Counter %> repetitions.


<% $url = $Request->ServerVariables('PATH_INFO')->item; $_ = $Request->ServerVariables('PATH_TRANSLATED')->item; s/[\/\\](\w*\.asp\Z)//m; $params = 'filename='."$1".'&URL='."$url"; $params =~ s#([^a-zA-Z0-9&_.:%/-\\]{1})#uc '%' . unpack('H2', $1)#eg; %> Return

view the source