PERL CGI Tutorial
for Writing Interactive Form Scripts

Searching a File

There are different ways of searching a file using PERL. We'll use a simple method using the match operator.

PERL uses patterns or regular expressions to compare strings. In the conditional statement below PERL searches $line for a pattern of characters placed within the forward slashes on the right. The ( =~ ) is PERL's match operator.

if ($line =~ /pattern/){
}

To search a file we must first open it and using the same techniques we used to display it, dump the contents into an array (list) of lines. We'll also use the split function to prepare the results for display.

In this CGI script we'll place the search string manually in the code. Under normal circumstances you would create a simple HTML form and ask the user to enter the search value. Then you would parse the form and your script would pick up with what we present here.

Note: If you would rather build the form and parse the data the code can be found in the CGI Script Gallery, Script #4

The code is the same as display_file.pl, with the exception of the conditional statement we placed within the foreach loop. Instead of displaying all of the contents it will only display data that matches the search criteria. The code of the conditional statement is marked in red. We also modified the print statement and added a title.

Replace Anderson with a name that you added to the file names.txt If you used the same last name more than once in your entries it will display all of them.

#!/usr/bin/perl
$search="Anderson";

open(INFO, "names.txt");
@array=<INFO>;
close (INFO);

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

print "<html>\n";
print "<head><title>Display File Contents</title></head>\n";
print "<body>\n";
print "<h4>Search Results</h4>\n";

foreach $line (@array){
if ($line =~ /$search/){
($last,$first)=split(/\|/,$line);
print "Your search returned: $first $last<br>\n";
}
}

print "</body>\n";
print "</html>\n";

Note: Be sure to change the line that specifies the search string to a name you have entered in the file.

Using Split Function Sorting a file
CGI Online is a service provided by Net Success 2000 Plus.
PO Box 1508
Somerset, KY 42502
Last Modified: October 9, 2007

| HTML TOC | Website Design Workshop | Home |