Saturday, March 01, 2003

CodeBit; Using Perl to Process HTML Form Information

I've found using a hash variable to hold form information to be the easiest way to work. The function shown below is called getFormData. It reads each form field into a hash, with either 'scalar_' or 'array_' prepended to the field names. This technique works well when you have form field with the same name, like checkboxes.

In order to effectively use this code, you need to be familiar with references. If you need a refresher on this topic, please see Chapter 8 of my book at http://www.CodeBits.com/p5be/ch08.cfm.

Here is the code that I place towards the top of my CGI scripts:

    getFormData(\%FORM);

The printFORM function is used for debugging. It prints all of the values in the FORM hash. Notice that it displays both scalar and array versions of the form data.

sub printFORM {
  print "Form Variables\n";
  print "--------------\n";

  foreach $key (sort(keys(%FORM))) {
    print "$key = @{$FORM{$key}}\n"
      if ref($FORM{$key}) eq "ARRAY";
    print "$key = $FORM{$key}\n"
      if ref($FORM{$key}) ne "ARRAY";
  }
}

And then towards the end of the script, I place the following routine:

sub getFormData {
  my($hashRef) = shift;
  my($buffer) = "";

  if ($ENV{'REQUEST_METHOD'} eq 'GET') {
    $buffer = $ENV{'QUERY_METHOD'};
  }
  else {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
  }

  foreach (split(/&/, $buffer)) {
    my($key, $value) = split(/=/, $_);

    $key = decodeURL($key);
    $value = decodeURL($value);

    $hashRef->{"scalar_$key"} = $value;

    if (! defined($hashRef->{"array_$key"})) {
      $hashRef->{"array_$key"} = [ $value ];
    }
    else {
      push @{$hashRef->{"array_$key"}}, $value;
    }
  }
}
Post a Comment