|
The for loop is another excellent control statement tool.
The basic syntax of a for loop follows:
for ([initial condition]; [test]; [incrementation])
{
[action to perform]
}
The "initial condition" defines where the loop should
begin. The "test" defines the logic of the loop by letting
the script know the conditions that determine the
scripts actions. The "incrementation" defines how the
script should perform the loop. For example, we might
produce a visible countdown with the following for loop:
for ($number = 10; $number >= 0; $number--)
{
print "$number\n";
}
The script would initially assign "10" to the scalar
variables $number. It would then test to see if $number
was greater than or equal to zero. Since ten is greater
than zero, the script would decrement $number by
subtracting one from the value of $number.
|
To decrement, you use $variable_name--. To increment, you use $variable_name++.
|
Executing the statement block, the script would then print
out the number nine. Then, it would go back through the
loop again and again, printing each decremented numbers
until $number was less than zero. At that point, the test
would fail and the for loop would exit.
|