RE: parsing forms with perl...

by "MILLER David R." <dmiller(at)mcc.ca>

 Date:  Wed, 28 Mar 2001 10:04:52 -0500
 To:  "hwg-languages (E-mail)" <hwg-languages(at)hwg.org>
  todo: View Thread, Original
When you put form info into a Perl hash:
	$formdata{$field} = $value;
you lose the original order. Hashes are great for storing key/value pairs,
but they do not preserve order, although of course you can sort hash keys
according to any criteria you want.

Solution 1:
You could put the values into an array instead of a hash, which would
preserve order but lose the name of the form widget:
	$formdata[$i++] = $value;
This is potentially dangerous, however, because some form widgets, notably
radio groups and checkboxes may return no values or multiple values.

Solution 2 (better):
If you know in advance the names of the form widgets, put *them* in an array
in the order you want:
	@widget_names = qw(widget1 widget 2 widget2a widget2b widget 3);
and then access the formdata hash thusly:
	foreach $widget_name(@widget_names) {
		print "$formdata{$widget_name}<br>\n";
	}

HTH

---------------FROM-------------------
David R. Miller
Manager, Computer-Based Testing
Medical Council of Canada
dmiller(at)mcc.ca
(613) 521-6012
(613) 521-9722 (fax)
-----------------------------------------

Original message:
Date: Sun, 25 Mar 2001 15:07:24 +1200
From: Web Services New Zealand <wsnz(at)ihug.co.nz>
Subject: parsing forms with perl...

Hi,

I'm using a fairly standard method of processing form input into variables, 
which I've pasted in below. My problem is that it comes out in alphabetical 
order of input type name, and I was hoping to retain it in the order that 
it appears in the form.

I normally do this sort of thing in C, which does this, and PERL is 
something I'm just having to use for this cgi. Any help as to what I need 
to do to stop the reordering?

Thanks
Kyle

/*
#!/usr/bin/perl

my $method = $ENV{'REQUEST_METHOD'};

if ($method eq "GET") {
     $rawdata = $ENV{'QUERY_STRING'};
} else {
    read(STDIN, $rawdata, $ENV{'CONTENT_LENGTH'});
}

my @value_pairs = split (/&/,$rawdata);
my %formdata = ();

foreach $pair (@value_pairs) {
     ($field, $value) = split (/=/,$pair);
     $value =~ tr/+/ /;
     $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
     $formdata{$field} = $value;
}

print "Content-type: text/html\n\n";
*/

HWG: hwg-languages mailing list archives, maintained by Webmasters @ IWA

This page is part of a preserved archive of archives.hwg.org. The site is no longer active and its content is not maintained. For enquiries about this archive, write to archive(at)iwanet.org.