Computer science: interpretation of the perl for loop

Tutoring math, you are likely aware of its connection to computer science.  The math tutor continues the explanation of the perl for loop.

In my previous post, I began exploring the field of computer science with a look at a for loop. The loop was written in perl. Now I will explain, line by line, the meaning of the loop code:

for ($i=0;$i<3;$i++){

print “The counter is now at $i.\n”;

}

First off, the dollar sign in front of the i means that i is a variable. In perl, a variable has a dollar sign in front of it to show it’s a variable. Programmers often call a counter variable i, j, or k. So $i means “the counter variable i”.

$i<3 means that as long as the value of i is less than three, the loop will continue running. When i equals 3, the program will exit the loop.

$i++ means that every time the program executes the loop, it adds 1 to the counter variable (also known as incrementing the counter variable by 1). Importantly, a for loop increments the counter variable at the end, rather than at the start.

The brace { means the program is entering the loop body, which contains the commands to be executed during each pass through the loop (also known as each iteration of the loop). In our case, there is only one instruction:

print “The counter is now at $i.\n”;

print means display what’s in the quotation marks. The $i is displayed as its value each time. Substituting the value of a variable in a quoted sentence is called interpolation. The \n means “newline”.

Now, the program reaches the closing brace }, which means the loop instructions are complete for this cycle. It’s time to increment the counter and return to the beginning of the loop. If $i<3, the loop will execute again.

Hence the output

The counter is now at 0.
The counter is now at 1.
The counter is now at 2.

Hope this clarifies the perl for loop. In a coming post I’ll mention how to get (or find) perl on your own system, should you want to experiment with the code yourself:)

Source: Robert Pepper’s Perl Tutorial. Robert taught me almost everything I know about perl:)

Tagged with: , , , , , ,

Leave a Reply