Table of Contents

A for Loop demonstrated

All well and good, but what if we want to load each element of the array in turn ? Well, we could build a for loop like this:

@names=("Muriel","Gavin","Susanne","Sarah","Anna","Paul","Trish","Simon");

for ($x=0; $x <= $#names; $x++) {
        print "$names[$x]\n"; 
}

which sets $x to 0, runs the loop once, then adds one to $x , checks it is less than $#names , if so carries on. By the way, that was your introduction to for loops. Just to go into a little detail there, the for loop has three parts to it:

In this case, the variable $x is initialised to 0. It is immediately tested to see if it is smaller than, or equal to $#names . If that is true, then the block is executed once. Critically, if it is not true the block is not executed at all.

Once the block has been executed, the modification expression is evaluated. That's $x++ . Then, the test condition is checked to see if the block should be executed or not.