In this tutorial, we will learn how the loop statement perform in Perl language. Loop statement is used when we need to execute a block code for several number of times. Let's us see which command we can use at this part.
While Loop
This is command will check the condition first before enter the loop. If the condition is true, it will execute the statement in the loop. If not, program control passes to the line immediately after the loop. Let's us see the example below.
While loop flow |
#!/usr/bin/perl
$var = 1;
while ($var<10)
{
print "var = $var\n";
$var++;
}
print "END\n";
$var = 1;
while ($var<10)
{
print "var = $var\n";
$var++;
}
print "END\n";
The above example should be work as the video below.
Do ... While Loop
In this part, we will learn do...while loop. It is a bit different with the while loop condition, this is because it checks its condition at the bottom of the loop. Thus, it will execute the statement first before doing the checking. Let's see what is the difference you can found from this example.
Do...While loop flow |
#!/usr/bin/perl
$var = 1;
do
{
print "var = $var\n";
$var++;
}while ($var<10);
print "END\n";
$var = 1;
do
{
print "var = $var\n";
$var++;
}while ($var<10);
print "END\n";
The following video shows the output of the above example.
For Loop
In this example, we will show you how the for loop is perform. For loop is a repetition control structure that allows us to write a loop that needs to execute in a specific number of times. The below example shows us how it works.
For loop flow |
#!/usr/bin/perl
for($i=0 ; $i<10; $i++)
{
print "Loop : $i\n";
}
print "END\n";
for($i=0 ; $i<10; $i++)
{
print "Loop : $i\n";
}
print "END\n";
The output of this example is shown as the video below.
Foreach Loop
Foreach loop is a powerful tool in Perl language. It iterates over a list values and sets the variable as each element of the list in turn. Let's us see how it performs.Foreach loop flow |
#!/usr/bin/perl
@name = ("Ali", "Abu", "AMei", "AKong");
foreach $a (@name)
{
print "Name = $a\n";
}
print "END\n";
@name = ("Ali", "Abu", "AMei", "AKong");
foreach $a (@name)
{
print "Name = $a\n";
}
print "END\n";
The source code above will be show the output as the video below.
All of the above example is the loop condition, we can used in the Perl language. In the next tutorial, we will show you how to use some special command to interrupt the loop statement.
No comments:
Post a Comment