Perl For Loops: A deep dive into the world of Perl’s for loops

perlforloopPerl is a high level, general purpose, interpreted programming language. It has a strong standing with over 25 years of development history. Though it started primarily for text manipulation, it has grown significantly and is now used for a diverse range of programming needs spanning system administration, web development and even GUI development. Due to this it is often referred to as the ‘swiss army knife’ or the ‘duct tape’ of the web programming world.

Its constructs are quite simple and user friendly. A novice can easily learn and start writing their own program. If you would like to get your hands dirty, here is a really good hands-on, step by step Perl Programming course to get you started.

The Perl language provides constructs to allow complex execution paths as per your need. In some cases you may need to execute a block of code repeatedly.  A loop lets you do just that – execute a block of code, over and over.  Perl has a few different kinds of loops, of which the most commonly used is the for loop.

In this tutorial, we are going to get into the details about Perl’s for loops – the syntax, constructs, the control parameters, and how to use them. We assume you have basic programming background, and that you already have Perl installed on your system. If not, we recommend you first look up the instructions to install perl from this excellent Perl Tutorial.

The for keyword in Perl can work in two ways – one as the basic 3-part C-style for loop and the second as the foreach loop scanning arrays.

The Basic FOR loop

This is the 3-part C style for loop where you can efficiently control the execution of a block of code, repetitively, based on certain conditions. Here is the the syntax for a for loop in Perl.

For Loop Syntax

for (initialize; condition; increment)  
{
      statements;
}

Here

  • initialize is where you initialize the conditionals for your loop.
  • condition is the actual expression you want to evaluate against in order to decide whether or not to execute the loop.
  • increment is the manner in which you want to update the control variable after each loop.
  • statement is the set of code you want execute in each loop.

The actual control flow or flow of execution is as follows

  1. The initialize step is executed only once, at the beginning of the loop. Here we declare and set the loop’s control variables. If left blank, it means you do not want to use a control variable, or you have set it elsewhere. The semicolons demarcate the parts of the control statement and are not optional.
  2. The second part of the control statement is the actual condition you want to test against, each time, before you execute the loop. It can be any boolean expression, but usually involves the control variable you had set in the initialize step. If this condition is true, the loop is executed. If the condition is false, we exit the loop and control passes to the next step after the loop.
  3. Once the loop is executed, control flows back to the increment  statement. This is your chance to update the control variables as required. This can actually be an increment, decrement, or any other kind of update.
  4. After this the condition is evaluated again, and control flows back to step #2.

Note that you can leave either of the three parts blank, but you need to indicate that this is deliberate, by ensuring the semicolons are in the right place.  As you can see, this is quite similar to the for loop in the C programming language.

For Loop Example

#!/usr/local/bin/perl
# for loop example
for( $x = 0; $x < 5; $x = $x + 1 )
{
    print "Value of x is $x\n";
}   
print “Done with the loop”;

Here we use a conditional variable x. The first $x = 0  initializes the control variable x to 0 at the start of our for loop. The second part of the statement $x < 5 means we want to loop for as long as x is less than 5. And the last part $x = $x + 1  means that after each loop, we want to increment x by 1. The body of the loop is a print statement where we are just printing out the current value of x.  When executed, this code would print out the following

Value of x is 0 
Value of x is 1 
Value of x is 2 
Value of x is 3 
Value of x is 4 
Done with the loop

Go ahead, try this out for yourself. If you need help installing Perl or instructions how to run it, you can look up this Perl Programming course.

This was a basic example, but more often than not, your actual for loop, is likely to be a bit more complex.  What if instead of a simple control variable, you wanted to loop through an array. After all, you are very likely to be using larger arrays to store your data. In that case, you do not want to have to fill in individual array members in to the control statement. Perl has an easy way out. A ready to use foreach loop. Let’s check that out as well.

The FOREACH loop

The foreach loop iterates over a set of values i.e. a list, and sets the control element to the values in the list. It may sound complicated, but it is not. Let us just go through the syntax and see a few examples.

Foreach Loop Syntax

foreach variable (list)  
{
      statements; 
}

Here

  • variable is your control variable.
  • list is the name of the list or array you want to iterate through.
  • statements is the set of code you want to execute in each loop.

The actual control flow or flow of execution is as follows

  1. variable is set to the first value in your list.
  2. The block of code in statements gets executed.
  3. After execution of the block, control loops back to the list, and variable is set to the next value in your list.
  4. We repeat steps 2 and 3 in this manner, until we have gone through all the values in your list.

Pretty neat right! It is a simple and powerful way to handle repetitive tasks through an array. Now that you have understood the syntax and how it works,  let us move on to a some examples

Foreach Loop Example 1

!/usr/local/bin/perl
@list = (10, 20, 30, 40, 50);
# foreach loop execution
foreach $x (@list)
{
     print "Value of x is $a\n";
} 
print “Done with the loop”;

This is a simple example. Here we have an array of 5 numbers and we print out the values in a loop. When this code is executed, we would get

Value of x is 10 
Value of x is 20 
Value of x is 30 
Value of x is 40 
Value of x is 50 
Done with the loop

To make it even simpler, you could also write this example as

!/usr/local/bin/perl
@list = (10, 20, 30, 40, 50);
# for loop execution
for $x (@list)
{
     print "Value of x is $a\n";
} 
print “Done with the loop”;

Perl would automatically interpret that the for keyword in this case maps to a foreach and translate it internally. The output for both pieces of code would be identical.  This brings us to a good point – when should you use a for loop vs a foreach loop? The for loop syntax is very generic and can be used for a wider range of conditions, even complex ones. The foreach loop however, is quite specific. It is a simple construct, meant only to loop through a list or array.

Lets look at another example now.

Foreach Loop Example 2: Looping through a contact list

!/usr/local/bin/perl
@myContacts = ('Larry', 'Curly', 'Moe');
print "This is my Contact list:\n"; 
foreach $name  (@myContacts) 
{
     print $name;
     print "\n";
}

Here we have a more meaningful list – a list with all of someone’s contacts. This person is obviously a big fan of the Three Stooges! What do you think the output would look like?  Go ahead, try it out for yourself and see.  You should get something like this:

This is my Contact list: 
Larry  
Curly 
Moe

Did you get that? Great! If not, go and try it out again. Double check, did you type it out right?

Foreach Loop Example 3 : Using range

!/usr/local/bin/perl
$sum=0;
# foreach loop execution
foreach $x (15..20)
{
    $sum = $sum + $x;
} 
print “Sum of numbers from 15 to 20 is $sum\n”;

Note that here we have not explicitly listed out the numbers. We just put a range 15..20. If your array is a simple range, you do not have to type out the whole thing. Perl does the hard work for you. You can just specify the range. After execution, this program would give

Sum of numbers from 15 to 20 is 105

This is fun isn’t it! Let’s move on to something a bit more exciting, and complex.

Foreach Loop Example 4: Combining with if conditions

!/usr/local/bin/perl
 $myFavourite = "Kate";
 @actress = ("Angelina", "Pamela", "Sandra", "Jennifer", "Kate");
 foreach $name (@actress)
 {
    if ($name eq $search)
    {
       $prompt = "$name is my favourite!\n";
       print $prompt;
       print "";
    }
    else
    {
       $prompt = "$name is not my favourite!\n";
       print $prompt;
       print "";
    }
 }

What do you think this program will do? Try it out before you move on.

In this program we first set our favourite actress’s name, and then loop through a list of actresses to check whether or not our favourite is on the list.  The output will be

Angelina is not my favourite!
Pamela is not my favourite!
Sandra is not my favourite!
Jennifer is not my favourite!
Kate is my favourite!

How to use nested loops

The beauty of the Perl loops is that they are basically simple. You can combine them with the other Perl constructs to make a simple program, or make it as complex as you want. With all the previous examples, we have gently pushed your limits and written better and longer programs as we went along. Let us take it up a notch further.  What if you want to loop through multiple tables or conditionals? Do you think you can nest the for loops? Perl does indeed allow you to nest the for loops. The syntax is pretty simple. Just repeat the for loops. Yes, it is that simple. Here is the syntax:

Nested For Loop Syntax

for ( init; condition; increment )
{
    for ( init; condition; increment )
    {
        statement(s);
    }
    statement(s);
}

Can you try out an example for this on your own? Go ahead and give it a shot.

The Infinite loop

If the conditionals to a for loop never become false, the loop never ends. It becomes an infinite for loop. In some corner cases, you may want to try this in your code, more for debugging, rather than production code. There is no separate syntax to the infinite loop.  A simple for loop will suffice, just do not list any of the control clauses. Here is a sample code snippet

Infinite Loop Example

#!/usr/local/bin/perl
# infinte loop example
for(  ; ;  )
{
   print "This is an infinite loop\n";
}

Of course you would want to get out of the infinite loop at some point of time! To do that, just press the Ctrl+C keys.

Phew! That was a really in depth study of the different uses of the for loop in Perl. We do hope this helps you get better in your Perl programming journey and that you enjoyed learning with us. Feel free to refer back to this tutorial or even the Perl Programming course we have, at any point of time. The best way to learn programming of course, is to actually do it.

Once you get a hang of Perl, you may want to expand your horizons and learn some C programming as well.