Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Read form values

by ast (Initiate)
on Jul 23, 2003 at 15:47 UTC ( #277217=sourcecode: print w/replies, xml ) Need Help??
Category: CGI Programming
Author/Contact Info
Description: I use this script for parsing values from URL without using CGI module. This is very usefull when you have some small CGI scripts and only want to get the values from a html form. All values will be stored in a hash %INPUT.
my %INPUT;
my ($buffer, $pair, $name, $value);
my @pairs;

if ($ENV{'REQUEST_METHOD'} eq "GET") {
  $buffer = $ENV{'QUERY_STRING'};
} elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
  read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
  ($name, $value) = split(/=/, $pair);
  $value =~ tr/+/ /;
  $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  $name =~ tr/+/ /;
  $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

  if (defined $INPUT{$name}) {
    $INPUT{$name} = $INPUT{$name}.",".$value;
  } else {
    $INPUT{$name} = $value;
Replies are listed 'Best First'.
(jeffa) Re: Read form values
by jeffa (Bishop) on Jul 23, 2003 at 16:14 UTC
    Unfortunately for you, it so much easier on the coder to add:
    use CGI qw(param);
    than it is to cut can copy this into a script, or make turn it into a module. We are big on code re-use at the Monastery. People constantly complain that is too bloated, but it rarely really ever is. Besides, what happens when you suddenly need to parse upload fields?

    Even though you do handle multiple fields, your code is going to break on a string like foo=one%20field&foo=two%2Cfield which should only yield two elements for foo, not three. For that matter, i prefer to deal with a list instead of being handed a delimited string that i have to split myself.

    UPDATE: observe how handles this:
    perl -MCGI=param -le"print for param(foo)" "foo=bar&foo=one%2Cfield"


    (the triplet paradiddle with high-hat)
Re: Read form values
by belg4mit (Prior) on Jul 23, 2003 at 16:04 UTC
    You might want to look at CGI::Simple and CGI::Lite. These are more robust than the code above without getting into the complexity of CGI.

    I'm not belgian but I play one on TV.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://277217]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2021-01-20 09:34 GMT
Find Nodes?
    Voting Booth?