FAQ 9.16 How do I decode a CGI form?
am 15.04.2008 09:03:02 von PerlFAQ ServerThis is an excerpt from the latest version perlfaq9.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
------------------------------------------------------------ --------
9.16: How do I decode a CGI form?
(contributed by brian d foy)
Use the CGI.pm module that comes with Perl. It's quick, it's easy, and
it actually does quite a bit of work to ensure things happen correctly.
It handles GET, POST, and HEAD requests, multipart forms, multivalued
fields, query string and message body combinations, and many other
things you probably don't want to think about.
It doesn't get much easier: the CGI module automatically parses the
input and makes each value available through the "param()" function.
use CGI qw(:standard);
my $total = param( 'price' ) + param( 'shipping' );
my @items = param( 'item' ); # multiple values, same field name
If you want an object-oriented approach, CGI.pm can do that too.
use CGI;
my $cgi = CGI->new();
my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' );
my @items = $cgi->param( 'item' );
You might also try CGI::Minimal which is a lightweight version of the
same thing. Other CGI::* modules on CPAN might work better for you, too.
Many people try to write their own decoder (or copy one from another
program) and then run into one of the many "gotchas" of the task. It's
much easier and less hassle to use CGI.pm.
------------------------------------------------------------ --------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.