2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2020

03/01/2003: How to Unset or Undefine Environment Variables Using Perl

How to Unset or Undefine Environment Variables Using Perl

Environment variables are stored as entries in the %ENV hash. Therefore you can use the delete() function to unset them. Sometimes unsetting environment variables is usefull to control the environment of a child process.

03/01/2003: Using Perl to Process HTML Form Information

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;
    }
  }
}