Page 12
Tidying Up the Input
To search for the info that corresponds to the user "title" input, we'll open the database in the same way we would any other file in Perl. Then we'll read it into an array variable and, of course, close the file.
open (DATA, "/usr/people/ferm/movies.dat");my @data = <DATA>;close (DATA);
The script now has the all the info from the database, and it's ready to scan for the specific info that matches the user input. We gave the user explicit instructions about how to type in the title of the movie, but you'll be amazed at how varied the input will actually be. To figure out what the hell the user's talking about, we'll just use the catchall that I showed you earlier.
Here's what it looks like: (Note my use of comments. You should use ones just like these; you could even provide a little more detail. They're extremely helpful.)
# Always remember to put this line at the top! #!/usr/local/bin/perl # This opens the movie database and saves it into the @data variable. open (DATA, "/usr/people/ferm/movies.dat"); my @data = <DATA>; close (DATA); # Have we forgotten already? This gets the input regardless of what # method was used and stores it into the $in variable. my $in; if ($ENV{'REQUEST_METHOD'} eq "GET") { $in = $ENV{'QUERY_STRING'}; } else { $in = <STDIN>; }
Of course, the user's input often needs a little massaging (in the tweaking sense, not the red-light sense). First off, we want to make sure that we don't have any funky characters that are sometimes created when input is translated into URI-readable code. (URI is the code that certain nonalphanumeric characters are translated into when the form is submitted, and it's the browser's ideal method of passing the info to the CGI.) To vacuum up any junk that may inadvertently be created, do this:
$in =~ s/%(..)/pack("c",hex($1))/ge;
This is a search-and-replace command that looks to see if any characters start with % and converts them into characters you and I can read. Then it leaves you with sweet-smelling input.
All right: Now we've got normal text, but there are still some problems. If the title is more than one word long, the $in variable's going to have "+" signs where the spaces should be. So:
$in =~ s/\+/ /g;
This is another standard, Perl search-and-replace function that searches out and destroys any "+" signs and replaces them with a space.
Finally, we need to move the data out of the variable $in, and give it a more descriptive name.
my %movie = split (/=/, $in);
This code splits up the line into the associative array %movie. Since the name of the form field was "title," the data is stored in the slot $movie{'title'}. While not strictly necessary, it helps me keep track of what's going on. (Then again, I've never been called quick. In fact, most people just use imaginative strings of unmentionable words to describe me. Ah, therapy!)
Now that we have the data, it's time to do something with it.