About Me

Friday 20 April 2012

PERL - For Loops

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:

1This is row 1
2This is row 2
3This is row 3
4This is row 4
5This 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:

1Steve
2Bill
3Connor
4Bradley
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.

0 comments:

Post a Comment