Contents | Up | Prev | Next |
The for loop enables us to iterate over a sequence of numbers and repeat the same set of operations for each number.
For example, the following program prints all the numbers from 1 to 100:
for $i (1..100) { print $i, "\n"; }
Some explanations about the syntax:
We can nest loops, so for example the following program prints the multiplication board:
for $y (1 .. 10) { for $x (1 .. 10) { $product = $y*$x; # Add as much whitespace as needed so the number will occupy # exactly 4 characters. for $whitespace (1 .. (4-length($product))) { print " "; } print $product; } # Move to the next line print "\n"; }
You may have noticed the program's comments. In perl comments start with the sharp sign (#) and extend to the end of the line. Writing the multiplication boards with the labels that indicate which numbers are being multiplied is left as an exercise to the reader.
Contents | Up | Prev | Next |
Written by Shlomi Fish