Broad Network


Perl foreach loop

Perl Basics – Part 13

Perl Course

Foreword: In this part of the series, I discuss the foreach-loop, which is an alternative to the for-loop.

By: Chrysanthus Date Published: 29 Mar 2015

Introduction

This is part 13 of my series, Perl Basics. In this part of the series, I discuss the foreach-loop, which is an alternative to the for-loop. You should have read the previous parts of the series before reaching here, as this is a continuation.

The for-loop Revisited
The following code displays the content of an array using a for-loop:

use strict;

my @theArr = ("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");

for (my $i = 0; $i < @theArr; ++$i)
    {
        print $theArr[$i], "\n";
    }

The first statement in the code is familiar. The second statement creates the array, with variable, @theArr. Then you have the for-construct. Let us look at what is inside the parentheses of the for-construct first, before we look at what is in the block of the construct.

There are three statements in the parentheses (brackets). The first one is “my $i = 0;” . It gives the starting index value of the iteration. The next statement is, “$i < @theArr;” . This is a statement with two operands: one on the left of < and the other one on the right. Since the one on the left is a scalar, the statement is in scalar context. So @theArr returns a scalar, which is the length of the array. (If you were in the list context, @theArr would have returned the list of elements in the array.). We saw a similar situation previously with the = operator, while here we have the < operator. The third statement in the parentheses increments $i against the next iteration.

Now, inside the block: Inside the block we have one statement. This statement prints the value of each element of the array. It also prints the newline character, \n. Note: the “\n” is not actually printed, but it sends the cursor of the console to the next line. Remember, $theArr[$i] gives the value of each element in the array. For the first iteration, $theArr[$i] would be $theArr[0], for the second, it would be $theArr[1], third, it would be $theArr[2], and so on; note the indices in the square brackets.

The foreach Construct
There is another loop construct, similar to the for-construct. In fact it does the same thing but in a different way. The syntax is:

foreach Vairable (List)
    {
        #do something
    }

You can read the above syntax as, “for each variable in list, do something”. Recall, an array is a list. Each array element identifier is a variable. For the above array, $theArr[0], $theArr[1], $theArr[2], etc are all variables. With arrays, the difference in the variable names is in the indices.

Now, read the foreach syntax again. The above for-loop is re-written below using the foreach construct (syntax).

use strict;

my @theArr = ("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");

foreach my $item (@theArr)
    {
        print $item, "\n";
    }

Each variable in the array is represented by the scalar, $item. Note the two places where $item has been used in the construct. The first time it is used in the foreach construct is in the first line; there you have the reserved word, my. The variable can be any scalar name you want. It simply identifies each of the array elements in each iteration. It replaces the would be $theArr[0], $theArr[1], $theArr[2], etc. Try the code.

List Literal
You can use a list literal in place of the array. The following code illustrates this:

use strict;

foreach my $var ('one', 'two', 'three')
    {
        print $var, "\n";
    }

No array was created in this code. You have just the list literal, ('one', 'two', 'three'). You should try the code sample, if you have not done so.

Which one do you use? The for-construct or the foreach construct. The Perl inventors prefer that we use the foreach construct, when the statements in the block are straightforward.

foreach and Hash
The foreach construct can be used with hashes. In the following code, the variable replaces the keys. Read and try the following code:

use strict;

my %fruitColor = (
                                 Apple => "purple",
                                 Banana => "yellow",
                                 Pear => "green",
                                 Lemon => "green"
                             );

foreach my $var (keys(%fruitColor))
    {
        print $fruitColor{$var}, "\n";
    }

The variable that replaces a key is $var. It occurs in the first line and in the block. The list that the foreach construct works on must be in parentheses, that is in (). The function, keys(%fruitColor), produces or returns the list of keys of the hash, %fruitColor. This return list stays in the parentheses. The variable is used in place of the hash keys in the block.

Hey, you can use the variable in place of the hash values, as well. Read and try the following code:

use strict;

my %fruitColor = (
                                 Apple => "purple",
                                 Banana => "yellow",
                                 Pear => "green",
                                 Lemon => "green"
                             );

foreach my $var (values(%fruitColor))
    {
        print $var, "\n";
    }

Note that the statement in the block has been changed from “$fruitColor{$var}” to “$var” as $var now refers to a value and not a key.

The variable, e.g. $var in the foreach loop is called the iterator variable.

Well, let us end here. We continue in the next part of the series. Always remember that any principle outlined in this series (volume) works with traditional Perl.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message