Armed with this basic working knowledge of Perl we can now return to our task of parsing the string of data received from an html form.
Remember the server receives the form data as one big string.
firstname=yourname&meaning=to+avoid+death
To parse it into its components we use the following steps.
Lets look at a perl program to do this
1 #!/usr/bin/perl
2
3 $forminfo = <STDIN>;
4 @key_value_pairs = split(/&/,$forminfo);
5 foreach $pair (@key_value_pairs){
6 ($key,$value) = split(/=/,$pair);
7 $value =~ s/\+/ /g;
8 $value =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("C", hex($1))/eg;
9 $FORM_DATA{$key} = $value;
10 }
11 print "Content-type: text/html \n\n";
12 print $FORM_DATA{'meaning'}, "\n\n";
13 exit (0);
(Note: Each line has been numbered for explanation purposes,
Do not include these numbers when you write the perl script.)
Lines 1 to 3 - provide the location of perl on the server and that uses a string variable $forminfo to store the incoming form data as a single string.
Line 4 - splits the string at each & and stores the key/value pairs in an array called @key_value_pairs.
Each element of this array is a string similar to the following
name=fred+nerk
where name is the name of a text box on the form and 'fred nerk' is the value the user entered into the text box when filling out the form.
Lines 5-10 - Loops through the @key_value_pairs array and
Line 6 - Splits the key/value at the equals sign into a key variable and a value variable,
Line 7 - substitute spaces for + signs in the value variable and
Line 8 - converts any hexadecimal codes into decimal equivalents.
Line 9 - stores the key value pairs in an associative array called $FORM_DATA.
Line 11 - Is the html header code
Line 12 - sends the contents of the original meaning of life text area back to the user
Line 13 - exits the code cleanly
Meaning of Life - Exercise 2
Modify the code so that it works with the form you created for the first
Meaning of Life exercise you built earlier in the course.
Make sure you send all the details the user typed into the form back to them nicely formatted.
Make sure you save your work.
Exercise
Write a perl script that takes the data entered by a user in an html form's text area and
returns it to them with every word capitalised.