in reply to Populating a Perl associative array with form values
In short, no, CGI won't do that for you, because that's not really its job. You can do it yourself pretty easily though. I'm going to simplify your example a little by using a dot instead of curlies.
<input name="form_item.foo" value="one"> <input name="form_item.bar" value="two"> <input name="form_item.fiddle" value="three">
Now you can "split" on the dot to nest the hashes. The code below works recursively, so you can have multiple dots in a field name and they will be broken into several levels of hashes.
sub nest_hash { my ($delim, $hash) = @_; my $new; while (my ($key, $value) = each %$hash) { unless ($key =~ /\Q$delim\E/s) { $new->{$key} = $value; next; } my ($before, $after) = ($`, $'); my $temp = nest_hash($delim, { $after => $value }); while (my ($k, $v) = each %$temp) { $new->{$before}{$k} = $v; } } return $new; } my $params = $q->param(); my $nested = nest_hash('.', $params); my $hashref = $nested->{form_item}; print $nested->{form_item}{foo}; # one print $hashref->{fiddle}; # three
Code is only partially tested.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Populating a Perl associative array with form values
by nenbrian (Acolyte) on Apr 30, 2004 at 17:28 UTC |