November 2018 Archives

Modern Perl CGI

This is a CGI script, let's call it uppercase.cgi:

#!/usr/bin/env perl
use strict;
use warnings;
use CGI;
use Encode::Simple;
use JSON::MaybeXS;
use Syntax::Keyword::Try;

my $cgi = CGI->new;
try {
  my $input = decode 'UTF-8', scalar $cgi->param('input');
  print $cgi->header('application/json; charset=UTF-8'), encode_json {output => uc $input};
} catch {
  print $cgi->header('text/html; charset=UTF-8', '500 Internal Server Error'), '<h1>An error has occurred.</h1>';
  die $@;
}

This is also a CGI script, that does all of the same things (and more):

#!/usr/bin/env perl
use Mojolicious::Lite;

any sub {
  my $c = shift;
  my $input = $c->param('input');
  $c->render(json => {output => uc $input});
};

app->start;

The second script, however, is also a FastCGI script, by changing the extension to .fcgi and the shebang to #!/usr/bin/env plackup -s FCGI. It's also a mod_perl script, by changing the extension to .psgi and using Plack::Handler::Apache2. It's also a standalone web application that supports websockets, by running it as ./uppercase.pl daemon or hypnotoad uppercase.pl.

Be concise. Be flexible. Be modern. Don't use CGI.pm.

(This article shows how a CGI script may be written with Mojolicious, but there are many other modern options that may suit your needs better while providing the same benefits that CGI.pm does not. See mstpan 1 and CGI::Alternatives.)

Reddit comments

About Grinnz

user-pic I blog about Perl.