Loops in Perl


Loops Perl – AyeSir.org

For Loop:-

Example-

#!/usr/local/bin/perl

# for loop example

for( $x = 0; $x < 10; $x = $x + 1 )

{

print “Value of x is $x\n”;

}

print “Completed Task”;

Here before the start of the loop, perl initializes the scalar variable $x to zero. It then checks the logical condition $x < 10. If the condition is true, perl will execute all the code between braces {} once. It will then increment $x by 1 based on counter $x +1. Once first iteration is done, the logical condition is checked again. This iteration will keep repeating till the logical condition becomes false after which it will exit the loop.

 

Results:

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

Value of x is 5

Value of x is 6

Value of x is 7

Value of x is 8

Value of x is 9

Value of x is 10

Completed task

 

Foreach Loop:-

This loop iterates over a list of values.

Example:

!/usr/local/bin/perl

@names = (‘Rocky’,’Vicky’,’Niky’);

# foreach loop execution

foreach $x (@names)

{

print “Name of x is $a\n”;

}

print “Completed task”;

Results:

Name of X is Rocky

Name of X is Vicky

Name of X is Niky

 



While Loop:-

While loop keeps on repeating a segment of code till the condition specified is false.

Examples-

$count =5;

While ($count >=1) {

Print “$count”;

$count –;

Print “Finished Counting\n”;

5 4 3 2 1

Until Loop:-

Until loop syntax is same as while loop. Only thing is that it does exactly opposite of what while loop does.

$count =5;

Until ($count ==1) {

Print “$count”;

$count–;

}

Results:

5 4 3 2




Do..While Loop:-

In Do.. while loop, the condition is checked after running the block of code so that at least once the code block gets executed unlike while statement if the condition becomes false at first check then block of code will not get executed even once.

$var =1

Do{

++$var;

Print “$var”;

} while $var <= 10;

Print “\n”;

Results:

2 3 4 5 6 7 8 9 10

Nested Loop:-

Perl loop can be nested inside another loop. Nesting is allowed for all above type of loop in perl.

Syntax:

Nested For Loop:

for (initialize; condition; increment){

for ( initialize; condition; increment ){

statement(s);

}

statement(s);

}

Nested While Loop:

while(condition){

while(condition){

statement(s);

}

statement(s);

}





Nested Do.. While Loop

{

statement(s);

do{

statement(s);

}while( condition );

}while( condition );

 

Nested Until Loop

until(condition){

until(condition){

statement(s);

}

statement(s);

}