The for Loop

A for loop takes the loop the number of times defined.
Here is the general form of a for loop:

for (starting assignment; test condition; increment)
{
code to repeat
}

Well, that’s great, but it doesn’t tell us much about what happens. Instead, let’s make a statement, “Linux Rocks” 10 times using a for loop like this:

[code]
for (\$count=1; \$count<11; \$count++)
{
print “Linux Rocks!n”;
}
[/code]

You’ll notice above we created a variable named \$count to test the condition each time through. In this case, we only used it to test the condition and not inside the loop itself. The first time through \$count is 1 since we have that as our starting condition. The loop will keep repeating until count finishes the 10th time through. When it tries to go through as 11, it is stopped because it fails the test condition- 11 is not less than 11. So, what we get is this repetitive list:

Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!

You could also use the \$count variable inside the for loop to change what is printed. This comes in handy when we get to arrays, but for now we will just print the value of \$count each time through. This will print a list of numbers from 1 to ten:

[code]
for (\$count=1; \$count<11; \$count++)
{
print “\$countn”;
}
[/code]

Now you will get this:

1
2
3
4
5
6
7
8
9
10

The while Loop

The while loop repeats a portion of code, but it reapeats it until the condition you provide comes back false. Here is the general syntax for the while loop:

while (test condition)
{
code to repeat
}

So, we could print out that list of numbers from one to ten with the while loop instead. Be sure to define your test variable (in our case \$count) before the loop begins. You will also need to be sure to increment the test variable inside the loop. Here is the code for the number list with a while loop:

[code]
\$count=1;

while (\$count<11)
{
print “\$countn”;
\$count++;
}
[/code]

For some things, this is easier to use than the for loop. It just depends on what action you wish to perform.

The foreach Loop

The foreach loop is one that is almost always used with some sort of array. We will have more use for it later. If you have an understanding of arrays, this will make a bit more sense:

[code]
foreach variable_name (array_name)
{
code to repeat
}
[/code]

An array is a way of storing a group of variables that makes them easy to access and manipulate later. The foreach loop takes each element of the array and operates on it with your code. Let’s say we had an array named @bank (The @ sign signals an array). Using the foreach loop, we could print out each element of the array. If we use the variable \$dollar to represent an element in the array, we could print out every \$dollar we have in the @bank, so to speak!

[code]
foreach \$dollar (@bank)
{
print “\$dollarn”;
}
[/code]