for (initialization_statement; continuation_condition; iteration_command) { statement_1; statement_2; ... }In this,
my @arr = (4, 1, 8); for(my $i=0; $i<=$#arr; $i=$i+1) { print qq{\$arr[$i] has value $arr[$i]\n}; }Note the use of the assignment
$i = $i + 1;in the for loop. Mathematically, this statement doesn't make sense, but in computer programming, it is a powerful concept - it means to assign a new value of $i to the old value of $i plus 1. Because this arises so often there is a shorthand available:
$i += 1; # add 1 to the current value $i -= 1; # subtract 1 from the current value $i *= 1; # multiply the current value by 1 $i /= 1; # divide the current value by 1Also, because adding (and subtracting) one from the current value is so common, these particular operations are given a further shortcut:
$i++; # increase $i by 1 $i--; # decrease $i by 1
It is important to recognize at what point in a for loop the various operations take place. When the loop is first entered, the initialization statement is executed, and the truthfulness of the continuation statement evaluated. If it's true, the block of statements between the curly braces are run through. The iteration command is then executed, and the truthfulness of the continuation condition evaluated. If true, the statements between the curly braces are executed again. This loop continues until the continuation condition is no longer satisfied, upon which the loop is terminated.