Turning data into Information
Previous - Opening, Reading and Outputting
a file to the web
Processing data
I want to read the data that we stored in the array @file.
This process is called iteration. Replace the join statement
(see previous page) with the following
highlighted code:
#!/usr/bin/perl
open (FILE,"../text/links.txt");
@file = <FILE>;
close FILE;
print "Content-Type: text/html\n\n";
foreach $item (@file){
print "<br>$item";
}
See it work
This foreach loop takes each element in the @file array and places it into the variable $item. We then process the value of $item in the statement block between the braces ( { } ).
Now for all the new code we get -- the exact same result! Yes. On purpose. Now with the statement block introduced, we can get into some easy "magic". Let's introduce the split function.
Turning data into information
Data is raw and unprocessed. Information is processed and useful. So far
the stuff you see in your browser is useless. Now let's get some results.
There are other ways of doing this, but this is a good way to see the
functionality from ground up. We are merely laying the first layer of
brick as we build this house.
#!/usr/bin/perl
open (FILE,"../text/links.txt");
@file = <FILE>;
close FILE;
print "Content-Type: text/html\n\n";
foreach $item (@file){
my($title,$url,$desc) = split(/\t/,$item);
print "<a href=\"$url\">$title</a><br>$desc";
}
See it work
We have replaced the statement block in the foreach function with two new
statements that introduce a number of new concepts. The "my" defines local
variables, or variables that only "live" within this statement block.
| Tab-delimited tables offer functionality, including
cross-platform features, so it is best to use the tab (\t in perl)
to define the columns, or fields, of the table. |
The split function divides the variable$item
at the tab (represented as \t) into three
distinct variables, $title, $url,
and $desc.
One final addition
Let's add a counter to our program so that folks visiting the site
know how many links we have in our file.
#!/usr/bin/perl
open (FILE,"../text/links.txt");
@file = <FILE>;
close FILE;
print "Content-Type: text/html\n\n";
$counter =0;
foreach $item (@file){
my($title,$url,$desc) = split(/\t/,$item);
print "<a href=\"$url\">$title</a><br>$desc<br>";
$counter = $counter + 1;
}
print "<br>There are $counter links in the file";
See it work
The three new lines initialize the field $counter to 0, add 1 to the
value of $counter and print the value of $counter at the end of the
program.
Return to Perl Help