Tricky way to instantiate a class in Perl

Today I started to design a CGI engine for my light weighted Perl Web container and I wanted to share my solution about how to instantiate the CGI class here.

Let’s see how a form works on Perl CGI:

1. User submit a form request,

<form action="/firstapp/" method="post"><select name="userid">
<option value="user1">1</option><option value="user2">2</option>
</select><select name="dbid">
<option value="db1">1</option>
<option value="db2">2</option></select>
<input type="submit" name="Submit" value="submit" />


2. The form request comes to server side in below format,

POST /firstapp/ HTTP/1.1
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Accept-Encoding: gzip, deflate
Accept-Language: en-us,en;q=0.5
Host: localhost:8080
Referer: http://localhost:8080/firstapp/login.html
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Content-Length: 37
Content-Type: application/x-www-form-urlencoded


3. On Server side, CGI engine injects parameters submitted via form ‘hahaid=haha2&abcid=abc1&Submit=submit’ to the action page ‘/firstapp/’,

4. Developer can access those paramters using method my  param(‘$key’); E.g,

use CGI qw(:standard);

my $userid  = param('userid'); # Here it will return value "user2".

In my CGI implementation, I design it as below process,

Step 1, 2 are the same as above as both are client operation.

Starting from Step 3,

On Server side, my CGI engine class,

sub new{
my $classname = shift;
my $self = {};
bless($self, $classname);
return $self;

sub _init {
my $self = shift;
if (@_) {
my %extra = @_;
my $paramstr = $extra{"PARAMS"};# PARAMS is a keyword here
if (defined $paramstr) {
my %params = getParams($paramstr);
@$self{keys %params} = values %params;

sub getParams{
my $s = shift;
my %params = {};
my @pairs = split(/\&/,$s);
foreach (@pairs){
my ($key, $value) = split(/=/,$_);
$params{$key} = $value;
return %params;

Step 4. Developer can access those paramters with below steps:

1. import my CGI,

use camelcgi;

2. Instantiate it,

my $cgiinst = camelcgi-&gt;new(PARAMS =&gt; $ARGV[0]); 
# In my HTTP Daemon, it will pass the request content to it 
# as $ARG[0] automatically.

# E.g, $ARGV[0]=”userid=user2&dbid=db1&Submit=submit”

3. Retrieve those parameters with,

$cgiinst-&gt;{userid} ;

Let’s summarize the snippet here,

use camelcgi;

my $cgiinst = camelcgi-&gt;new(PARAMS =&gt; $ARGV[0]);

$cgiinst-&gt;{userid} ;

It is tricky, right? 🙂