PERL - For Loops
A for loop counts through a range of numbers, running a block of code each time it iterates through the loop. The syntax is for($start_num, Range, $increment) { code to execute }. A for loop needs 3 items placed inside of the conditional statement to be successful. First a starting point, then a range operator, and finally the incrementing value. Below is the example.
forloop.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n";
# SET UP THE HTML TABLE
print "<table border='1'>";
# START THE LOOP, $i is the most common counter name for a loop!
for($i = 1; $i < 5; $i++) {
# PRINT A NEW ROW EACH TIME THROUGH W/ INCREMENT
print "<tr><td>$i</td><td>This is row $i</td></tr>";
}
# FINISH THE TABLE
print "</table>";
forloop.pl:
1 | This is row 1 |
2 | This is row 2 |
3 | This is row 3 |
4 | This is row 4 |
5 | This is row 5 |
We looped through one variable and incremented it. Using HTML, we were able to make a nice table to demonstrate our results.
PERL - Foreach Loops
Foreach is designed to work with arrays. Say you want to execute some code foreach element within an array. Here's how you might go about it.
foreachloop.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
# SET UP THE HTML TABLE
print "<table border='1'>";
# CREATE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
# SET A COUNT VARIABLE
$count = 1;
# BEGIN THE LOOP
foreach $names(@names) {
print "<tr><td>$count</td><td>$names</td></tr>";
$count++;
}
print "</table>";
foreachloop.pl:
1 | Steve |
2 | Bill |
3 | Connor |
4 | Bradley |
We placed a table row counter for you to see each line more clearly. We use the variable $names to pull single elements from our array, PERL does the rest for us by looping through each element in our array. Use the sorting functions outlined in the PERL Arrays lesson.
Found Something Wrong in this Lesson?Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time! |