in reply to Initializing Hashes of Hashes (of Hashes)

Thanks all for the suggestions and apologies for the shonky question. I was hurrying to leave work and didn't have time to explain/contextualize it all (see below).

The reason I asked in the first place was that my 3 code efforts to fill out the hash all seemed inelegant and I hoped to be shown a better way. I did it iteratively like bart does in his response, handling the last segment separately. I don't like the recursive option given. CGI::State's method is pretty wacky, he loves the hook ops.

I still suspect I'm missing a better way though...

For those interested my code as I left it was:

sub cgi2args { my $cgi = shift; #my $cgi = CGI->new('a.b.c=3&a.b.c=4&x.y=4'); # a & a.b ? warn my $args = {}; for my $name ($cgi->param) { # could warn unrecognized for html typos #for my $name (grep $interface_re, $cgi->param) { my @segments = split /\./, $name; my $last_seg = pop @segments; my $a = $args; for (@segments) { $a->{$_} ||= {}; # XXX defined not true $a = $a->{$_}; } my @values = $cgi->param($name); $a->{$last_seg} = @values == 1 ? $values[0] : \@values; } return $args; }
Context
I have some classes for validating and storing data along with other scaffolding and am attempting to keep most of them unaware of CGI so that I can reuse them in non-web environments. This was a path (blind alley?) I wandered down on the way.

The two goals are:
1) Turn form data into complex data structures, generically enough that the backend can remain ignorant of the web.
2) Separate the parameters for different widgets. A widget sees all and only it's parameters.

CGI::State seems to do what is required.

Comment on Criticisms
All fairly valid. I knew the question was poorly framed and that the method was flawed. Nevertheless, I got some useful answers. Thanks.

Brad

Replies are listed 'Best First'.
Re: Re: Initializing Hashes of Hashes (of Hashes)
by bsb (Priest) on Apr 29, 2003 at 07:51 UTC
    (hmm, talking to myself..)
    An updated and safer (I hope) version.
    I stole some ideas from CGI::State and a piece of TT2's variable naming.