Parsing the QUERY_STRING

Let's write a CGI script that parses the QUERY_STRING:


use strict;

use warnings;

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

print "<html>\n";

print "<head>\n";

print "<title>Environment Variables</title>\n";

print "</head>\n";

print "<body>\n";

print "<H1>My Environment Variables</H1>\n";


if (exists $ENV{'QUERY_STRING'}) {

    my $qstr = $ENV{'QUERY_STRING'};

    my @settings = split /&/, $qstr;


    foreach my $s (@settings) {

        my @items = split /=/, $s;

        next unless (@items == 2);

        print "<P>$items[0] = $items[1]</P>\n";




print "</body>\n";

print "</html>\n";



This Perl code introduces a few more features of Perl. The exists command is a way to test for a specific key in a hash variable. The split command provides the ability to break up a single string into a list of substrings.

All this code does is test for the existence of the QUERY_STRING environment variable, and if it exists then split it up on the '&' symbol to separate the environment variable assignments from each other, and then split up each assignment into the variable name and its setting.

We can run it to make sure there's no errors:

ubuntu@ubuntu:~$ cp env.cgi query.cgi

ubuntu@ubuntu:~$ emacs -nw query.cgi

ubuntu@ubuntu:~$ ./query.cgi

Content-type: text/html




<title>Environment Variables</title>



<H1>My Environment Variables</H1>



ubuntu@ubuntu:~$ sudo cp query.cgi /var/www/cgi-bin/



We see nothing in the output because there's no QUERY_STRING environment variable set in your environment.

When you see no errors and you are happy with the script, copy it to /var/www/cgi-bin and then append the following to your Raspberry Pi IP address: /cgi-bin/query.cgi?1073=force&195=cyberknights&3538=robojackets&230=gaelhawks. What do you see?


If you see the winning alliance from the Curie Division at the 2019 Detroit World Championships, then your code is working perfectly! :-)