Monday, July 18, 2011

while loop perl

while loop is used to repeat block of statement

Syntax :
It can be used as do-while loop or simply while loop
1)

do
{
STATEMENTS
}while (CONDITION);
In this case the statements gets executed atleast once.For the next iteration the condition in the until has to be true.

2)

while(CONDITION)
{
STATEMENTS;
}
In this case the statements will be executed only when the condition is true.

Example:

1)
Content of the perl file:

$num=20;
do
{
print "the num is $num";
$num++;
}
while($num < 30 )

OUTPUT:

G:\perl_programs>perl perl_while.pl
the num is 20
the num is 21
the num is 22
the num is 23
the num is 24
the num is 25
the num is 26
the num is 27
the num is 28
the num is 29

G:\perl_programs>
2)
Content of the perl file:

$num=20;
while( $num < 30) { print "the num is $num"; $num++; }

OUTPUT: 

G:\perl_programs>perl perl_while.pl
the num is 20
the num is 21
the num is 22
the num is 23
the num is 24
the num is 25
the num is 26
the num is 27
the num is 28
the num is 29

G:\perl_programs>

The main differece between the two in the case of do loop statement will be executed atleast one irrespective of the condition is true or false.

No comments:

Post a Comment