Broad Network


Perl for and foreach Loops

Perl Syntax – Part 6

Perl Course

Foreword: In this part of the series, I talk about Perl for and foreach loops.

By: Chrysanthus Date Published: 13 Jun 2015

Introduction

This is part 6 of my series, Perl Syntax. In this part of the series, I talk about Perl for and foreach loops. You should have read the previous parts of the series before reaching here, as this is a continuation. Remember, the for and foreach loops are examples of compound statements in Perl.

The foreach Syntaxes
The foreach syntaxes are as follows.

    LABEL foreach (EXPR; EXPR; EXPR) BLOCK
    LABEL foreach VAR (LIST) BLOCK
    LABEL foreach VAR (LIST) BLOCK continue BLOCK

LABEL is optional depending whether or not you need to come back to the beginning loop point.

The first foreach syntax is,

    LABEL foreach (EXPR; EXPR; EXPR) BLOCK

This is known as the C-style for loop. An example code for this syntax is:

    for (my $n=0; $n<5; ++$n)
        {
            print $n; print "\n";
        }

Other statements can go into the block. The output for this particular code is,

0
1
2
3
4

Comparing this example loop with the first foreach syntax, the first EXPR in the parentheses is “$n=0”, the second EXPR in the parentheses is “$n<5” and the third EXPR in the parentheses is “++$n”. The first EXPR initializes the iteration counting variable. The second EXPR is the condition for the equivalent while loop. The third EXPR is the incrementing expression for the loop to go to the next iteration.

The second foreach syntax is:

    LABEL foreach VAR (LIST) BLOCK

This is equivalent in purpose to the C-style for loop (first foreach syntax above). However it is faster than the C-style for loop. This second syntax is what you should be using instead of the C-style loop.

In this second loop, LABEL is still optional, but is likely to be used. VAR also has to be used. If it is not used, the special variable, $_ will take its place. This second foreach syntax can be read as follows: For Each Variable in the LIST, carry out all the statements in the block on the variable. This does exactly the same thing that the C-style loop does, but faster. The above example code is re-coded in Perl style as follows:

    LOOP: foreach my $item (0..4)
        {
            print $item; print "\n";
        }

The output is the same as for the C-style code, i.e.

0
1
2
3
4

The label, LOOP could be omitted, as it was not used in the loop. The list is (0..4). Here, the two consecutive dots is known as the range operator. It substitutes all the un-typed numbers, to form the list. In the code, $item is in the place of VAR of the syntax. It is preceded by my, because of the use of strict mode. The Label has been typed, but it has not been used. It can be omitted in this case.

An array can be used in the place of the list, but it has to be placed in parentheses. Try the following code:

use strict;

    my @arr = ('John', 'Peter', 'Mary');

    LOOP: foreach my $item (@arr)
        {
            print $item, "\n";
        }

The output is:

John
Peter
Mary

Always use the Perl-style of the foreach loop instead of the C-style for loop, because the Perl-style is faster (when operated in Perl).

If you do not type the substitute for VAR of the syntax, $_ will take its place as in the following code:

use strict;

    my @arr = ('John', 'Peter', 'Mary');

    foreach (@arr)
        {
            print $_, "\n";
        }

The third syntax is:

    LABEL foreach VAR (LIST) BLOCK continue BLOCK

This syntax is similar to the second foreach syntax except that it has the continue block. The continue block is an auxiliary block that is executed after the block of interest has been executed. If you want a counter that is incremented as the loop moves from one iteration to the next, use the continue block for the incrementing expression.

The following code is the above Perl-style code modified:

use strict;

    my @arr = ('John', 'Peter', 'Mary');
    my $i = 1; #counter

    LOOP: foreach my $item (@arr)
        {
            print "number $i is ", $item, "\n";
        }
    continue
        {
            ++$i;
        }

The output is:

    number 1 is John
    number 2 is Peter
    number 3 is Mary

In this code, the initialization of the counter is done outside the loop (and the incrementing is done in the continue block).

For this code, if you do not want to initialize outside the loop and if you do not want the continue block, use the following code to have the same result:

use strict;

    my @arr = ('John', 'Peter', 'Mary');

    LOOP: foreach (1..@arr)
        {
            print "number $_ is ", $arr[$_-1], "\n";
        }

The list begins from 1 to the length of the array. In the block, the numbers in the list are gotten from $_ .

Above you have three foreach syntaxes. The first one is the C-style syntax. The second and third are the Perl-style syntaxes. You should always use the Perl-style syntaxes because they are faster.

Nested foreach Loops
Assume that you want to display the following numbers in their particular order given:

00, 01, 02, 03
10, 11, 12, 13
20, 21, 22, 23

The C-style code to do this is:

use strict;

    for (my $i=0; $i<3; ++$i)
        {
            for (my $j=0; $j<4; ++$j)
                {
                    print $i; print $j; print ", ";
                }
            print "\n";
        }

$i is for the rows and $j is for the columns. The perl-style, which is what you should use because it is faster, is as follows:

use strict;

    OUTER: foreach my $i (0..2)
        {
            INNER: foreach my $j (0..3)
                {
                    print $i; print $j; print ", ";
                }
            print "\n";
        }

Here, each counter and its VAR (of the syntax), is the same variable. Two labels are in the code, but they have not been used. They could be omitted.

The for Syntaxes
The for syntaxes are:

    LABEL for (EXPR; EXPR; EXPR) BLOCK
    LABEL for VAR (LIST) BLOCK
    LABEL for VAR (LIST) BLOCK continue BLOCK

Now, in Perl, “for” is a synonym for “foreach”. So if you go to all the above code samples and replace all the “foreach’s” with “for’s”, the output will still be the same. All the above code samples are repeated below with the “foreach’s” replaced with “for’s”. You can try the code samples. The labels have not been included since they were not used.

use strict;

    for my $item (0..4)
        {
            print $item; print "\n";
        }


use strict;

    my @arr = ('John', 'Peter', 'Mary');

    for my $item (@arr)
        {
            print $item, "\n";
        }


use strict;

    my @arr = ('John', 'Peter', 'Mary');

    for (@arr)
        {
            print $_, "\n";
        }


use strict;

    my @arr = ('John', 'Peter', 'Mary');
    my $i = 1; #counter

    for my $item (@arr)
        {
            print "number $i is ", $item, "\n";
        }
    continue
        {
            ++$i;
        }


use strict;

    for my $i (0..2)
        {
            for my $j (0..3)
                {
                    print $i; print $j; print ", ";
                }
            print "\n";
        }

That is it for this part of the series. We stop here and continue in the next part.

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