PERL - While
While loops continually reiterate 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 reiterations of code. These functions allow you to control the flow of your while loops.
- Next
Next is a block of code that is executed after the loop is finished, but before the loop is evaluated for the next iteration
- Last
Last stops the looping immediately (like break)
- Redo
Redo will execute the same iteration over again.
- Continue
Works with the next feature to interrupt the loop
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
if ($count == 4) {
print "Skip Four!<br />";
$count ++;
next;
}
# PRINT THE COUNTER AS USUAL
print $count."<br />";
$count ++;
}
continue {
print $count."<br />";
$count++;
};
print "Loop Finished!";
flowcontrol.pl:
0
1
2
3
Skip Four!
5
6
7
Finished Counting!
Above, we skip the fourth reiteration 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 reiterates 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:
| 1 | Steve |
| 2 | Bill |
| 3 | Connor |
| 4 | Bradley |
|