About Me

Friday 20 April 2012

PERL - While

PERL - While

While loops continually iterate as long as the conditional statement remains true. It is very easy to write a conditional statement that will run forever especially at the beginner level of coding. On a more positive note, while loops are probably the easiest to understand. The syntax is while (coditional statement) { execute code; }.

whilecounter.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET A VARIABLE
$count = 0;

# RUN A WHILE LOOP
while ($count <= 7) {
 # PRINT THE VARIABLE AND AN HTML LINE BREAK
 print "$count<br />";
 # INCREMENT THE VARIABLE EACH TIME
 $count ++;
}
print "Finished Counting!";

whilecounter.pl:

0
1
2
3
4
5
6
7
Finished Counting!

PERL - Next, Last, and Redo

Outlined below are several interrupts that can be used to redo or even skip iterations of code. These functions allow you to control the flow of your while loops.
Next
Place it inside your loop and it will stop the current iteration and go on to the next one.
Continue
Executed after each loop iteration and before the conditional statement is evaluated. A good place to increment counters.
Last
Last stops the looping immediately (like break)
Redo
Redo will execute the same iteration over again.

flowcontrol.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET A VARIABLE
$count = 0;
while ($count <= 7) {
  
 # SET A CONDITIONAL STATEMENT TO INTERRUPT @ 4
 if ($count == 4) {
  print "Skip Four!<br />";
  next;
 }
 # PRINT THE COUNTER
 print $count."<br />";

}
 continue {
  $count++;
 };
print "Loop Finished!";

flowcontrol.pl:

0
1
2
3
Skip Four!
5
6
7
Finished Counting!
Above, we skip the fourth iteration by incrementing the variable again. In the example we also print a line, "Skip Four!" just to make things easier to follow.

PERL - While Array Loop

Here we are just showing a method of looping through an array using a while loop. We use three variables to do this including: the array, a counter, and an index number so that each time the while loop iterates we also loop through each index of the array.

whilearrayloop.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET UP AN HTML TABLE
print "<table border='1'>";

# DEFINE AN ARRAY
@names = qw(Steve Bill Connor Bradley);

# COUNTER - COUNTS EACH ROW
$count = 1;

# COUNTS EACH ELEMENT OF THE ARRAY
$n = 0;

# USE THE SCALAR FORM OF ARRAY
while ($names[$n]) {
 print "<tr><td>$count</td><td>$names[$n]</td></tr>";
 $n++;
 $count++;
}
print "</table>";

while.pl:

1Steve
2Bill
3Connor
4Bradley

0 comments:

Post a Comment