Reading input into your CGI program isn’t rocket science, but the code to do it is a little more complex than what we’ve dealt with so far. The good news is that you don’t need to think about it because it’s already written for you!
Most Perl installs will come with a module called the CGI.pm module. It’s very handy, and allows you to read input to your program easily (as well as simplifying other tasks).
What you need to know in order to read input from your users is how to use CGI.pm in order to read input from your forms. The first thing you need to do is put the following line near the beginning of your program:
I’d put it either right before, or right after my use STRICT; line. This tells the Perl interpreter that you want to use a module, and will make all the code from that module available for your use.
Modules comply with what is known as Object Oriented programming. That means that in order to use the code supplied by a module, you first have to create an object, or “instance” of that module. This will be a variable that will be used to access all of the functions available by that module. This is how you’d declare a new instance of the CGI.pm module:
Don’t ask me why, but the most common variable name used for creating an instance of CGI is $q. Of course, you can make the variable name whatever you want.
So, let’s say you had a textbox named country in a form that's being submitted to your Perl CGI script. You’d access the information from that text box using your $q variable. For easy access later, it’s common to assign the value to another variable early in the program:
And that’s how you access each of the values that would be set up in your input forms. From then on after this line you can access the value that the user has typed in through the variable $country.
my $country = $q->param(“country”);
When you’re dealing with checkboxes, the checkbox will show as being activated by having “on” as it’s value. Radio buttons will work exactly the same way as other input types, it’s value will be set to the value of the option that was selected.
There are lots of other handy features that you can use with the CGI.pm module, we’ll be discussing those in future lessons. But these are the solid basics that you'll need to know in order to access variables in Perl and create CGI scripts that actually interact with the user.