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.
WE created a very simple form (search-entry-form.pl) that prompts the user for a first name.
TRY This Website Builder FREE!
No Credit Card Needed!
Create beautiful,professional websites
WITHOUT Learning to Code!!
Use this Next Generation Builder
to make blogs, portfolios or
full blown websites.
No Experience Needed!
Professional websites
Without the HASSLE!
Note: A similar form can be found in our free 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.
If you used the same first name more than once in your entries it will display all of them.
search.pl
#!/usr/bin/perl
read(STDIN, $buffer,$ENV{'CONTENT_LENGTH'});
$buffer =~ tr/+/ /;
$buffer =~ s/\r/ /g;
$buffer =~ s/\n/ /g;
@pairs = split(/&/,$buffer);
foreach $pair(@pairs){
($key,$value)=split(/=/,$pair);
$formdata{$key}.="$value";
}
$search=$formdata{'first'};
$counter= 0;
$records= 0;
open(INFO, "names.txt");
@array=<INFO>;
close (INFO);
print "Content-type:text/html\n\n";
print "<html>\n";
print "<head><title>Display Search Results</title></head>\n";
print "<body>\n";
print "<h4>Search Results</h4>\n";
foreach $line (@array){
if ($line =~ /$search/){
$records= ++$counter;
($last,$first)=split(/\|/,$line);
print "Your search returned: $first $last
\n";
}
}
if ($records== 0) {
print"No records found\n";
}
print "</body>\n";
print "</html>\n";
We took the code from the parse script to process the $first entry from the search-entry-form.pl script shown below.
We also added a little counter which increments the $counter variable if records are found. If it finds no results it returns a message.
The search is case sensitive.
search-entry-form.pl
#!/usr/bin/perl
print "Content-type:text/html\n\n";
print "<html>\n";
print "<head><title>Sample Form</title></head>\n";
print "<body>\n";
print "<form method=POST action=search.pl>\n";
print "<pre>\n";
print "Enter First Name:<input type=text name=first size=20>\n";
print "<input type=submit value=Submit><input type=reset>\n";
print "</pre>\n";
print "</form>\n";
print "</body>\n";
print "</html>\n";


