The “for” Loop Keyword in Perl : An Overview

perl operatorsPerl is a high level, dynamic and general purpose language developed by Larry Wall. It contains Perl 5 and Perl 6 in its family. Perl was basically developed for text processing. PERL stands for Practical Extraction and Report Language. It can run on a variety of platforms such as MAC OS, Windows and different versions of UNIX. It was originally developed for the UNIX shell replacement for helping system administrators to be more productive. We are going to discuss about the “for” keyword in Perl. It’s also known as C-style; however, it is used in various other programming languages.

Learn more about Perl programming through a course at Udemy.com

Looping in PERL:

Sometimes you may be in a situation where you need to execute a particular block of code several times. A loop in programming gives us the flexibility to execute a block of code.

Perl language provides us with loops such as “for”, “for each”, “while”, “until”, “do…While and NESTED” for handling different iterative statements. In any language whether it is C, C++ or Java, “for” loop is the most commonly used loop among all the loops. It loops through a particular block of statements until a specified condition is met.

General syntax of C-style for loop/For loop:

For (initialization;condition;updation)

{

Your code

…….

}

Example:

Use feature qw/say/;

# print numbers from 1 to 10

For (my $x=1; $x<11; $x++)

{

Say $x; // printing values of ‘x’

}

Let’s try to analyze the code shown above. Here, we import the feature ‘say’ in Perl, which works similar to the “printf” statement, but the only difference is that it also adds a new line into the printed string. Before the beginning of the loop, Perl will initialize the $x as 1 and after that it moves on to the condition part and checks whether the condition $x<11 is true or not. If the condition is false, it will immediately stop the loop. If the condition is true, it will execute the code inside the curly braces once. After this, it will go to the update part and update the variable as specified in the code shown above and it will increase the $x by 1. After the update, it will again go to the condition part and check the condition for a true or false value. Then, the loop executes the code according to the condition. As shown in the code above, it will execute and print from 1 to 10 and will finally stop when the condition becomes false.

Similarly, if you want to print numbers from 100 to 1, then the code will look like this:

Use feature qw/say/;

# print numbers from 100 to 1

For (my $x=100; $x>0; $x++)

{

Say $x; //printing values of ‘x’

}

A C-style for loop can also be used for accessing the array elements.

Example:

Use feature qw/say/;

my @cars_elements=(‘nissan’,’volksswagen’,’hyundai’,’honda’); //defining the array

for (my $x=0; $x<@cars_elements; $x++)

{

say cars_elements[$x];// printing the elements of array

}

It should be noted that the count has started from zero. It is because an array’s index starts at 0 in Perl. Arrays are used only as logical conditions such as <@cars_elements.The above loop will return the length of the array, which is 4.

For loops and array:

There is a simpler way in Perl for writing the above array code. If we pass an array to the “for” loop, then it will iterate through each and every element of the array until it reaches the end of the array. Consider the example below:

Use feature qw/say/;

my @cars_elements=(‘nissan’,’volksswagen’,’hyundai’,’honda’);//defining the array

for my $cars_element (@cars_elements)

{

say  $cars_element;// printing the elements of array

}

In this example, Perl will iterate through every element of array and will assign the current element value to the $cars_element. When the loop stops, the scope of $cars_element will run out. We can further simplify the above example without using any scalar variable in the argument. In this case, “$_” will be used by Perl as a temporary variable.

Use feature qw/say/;

my @cars_elements=(‘nissan’,’volksswagen’,’hyundai’,’honda’);//defining the array

for (@cars_elements)

{

say  $_;// printing the elements of array

}

For each in Perl:

You can use bot “for” and “foreach” in your code and both will work similarly. Now let’s take an example of “foreach” loop for the above code.

Example:

Use feature qw/say/;

my @cars_elements=(‘nissan’,’volksswagen’,’hyundai’,’honda’);//defining the array

foreach (@cars_elements)

{

say  $_; // printing the elements of array

}

Sometimes, you just need to perform looping n number of times in your code. In Perl, you can use a range from x to n in these scenarios.

Example:

Use feature qw/say/;

For (1..5)

{

say int (rand(60) + 2); /* it will print the values after getting from the expression “(rand(60) + 2” which would be of integer type*/

}

redo, next and last function of for loop in Perl:

To control the loop iteration, Perl provides different functions such as the  redo function, which runs the current iteration again.

Example:

for (1..6) {

my $num = int(rand(60)) + 2;

redo if $num == 15;

say $num;

}

In this example if number 15 is generated, then “redo” will again start the iteration and “say $num” will not be executed.

The other function is “next,” which moves to the next iteration and stops the current one.

Example:

@list=(1,2,3,4,10,10,3,6,7,1);

 

foreach $val(@list)

{

if( $val==10)

{

next;

}

Else

{

print" value is $val \n";

}

}

The above code will initially print the values 1,2,3,4 and will ignore the value 10, because the “next” function moves to the next iteration and ignores the current one. So, it ignores “10” two times and after that, it will again continue from the next iteration and prints the next values, which are 3,6,7,1.

The next function is the “last” function, which exits from the loop entirely after finishing the current iteration.

Learn everything about Perl 5 by taking a course at Udemy.com

Example:

my $var = '$scalar';

my @perlvar = ('^\$', '^@', '^%');

foreach (@perlvar )

{

if ($var =~ m/$_/)

{

say "it’s a match with $_";

last;

}

}

In the above example, if the condition found is true, the “if” block is executed and the “last” keyword in it stops any further iterations of the loop.

Conclusion

The for loop allows us to iterate over the elements of a list. For and foreach loops are interchangeable in Perl. We can replace the keyword foreach in place of for and both will work in the same manner. The for loop in Perl is very useful and easy to read and write. Perl supports C-style for loop; however, it is not recommended to use C-style for loop, because it will make the code less readable.