Paul Lalli wrote:
> Allan Houston wrote:
>
>>I've searched and read about everything I can find on trying to do this,
>>but my only solution I can think of is real, real ugly..
>>
>>Basically I'm looking to create a sub routine which will query a
>>database table for the specified rows, and create a hash where each
>>column is a key in the hash of hashes.
>
> <snip>
>
>>The problem being that I'm trying to create a function which will read
>>in say the first $count columns and return a hash of hashes with a depth
>>of $count keys.
>
>
> I strongly suspect an AB problem here. Why exactly do you feel the
> need to create such a function? What is your *actual* goal?
>
>
>>There has to be a more elegant solution than this surely.. Can anyone
>>point me in the right direction please ?
>
>
> I don't understand *why* you'd want to do this, but I believe this
> meets your criteria:
>
> #!/usr/bin/perl
> use strict;
> use warnings;
> use Data:
umper;
>
> my @stuff = qw/foo bar baz bam boom/;
>
> my %h;
> my $ref = \%h;
> for my $level (@stuff){
> $ref->{$level} = {};
> $ref = $ref->{$level};
> }
>
> print Dumper(\%h);
>
> __END__
>
>
> $VAR1 = {
> 'foo' => {
> 'bar' => {
> 'baz' => {
> 'bam' => {
> 'boom' => {}
> }
> }
> }
> }
> };
>
>
>
>
> Paul Lalli
>
Hi Paul,
First off - thanks for your code, its certainly helped me.
The reason I'm doing it this way is that the DBI fetchrow_hashref will
overwrite values where the key has multiple values which is how my data
is stored (unfortunately..)
The sub I'm writing allows me to specify an array of arbitrary columns
and get them returned in a hash hierarchy, which I find useful for
getting at the data quickly and easily.
Far more importantly however, you've shown me how to do something in
perl which I didn't know before - thank you
I made some minor changes to the code you provided to cope with the
multiple key values :
#!/usr/bin/perl
use strict;
use warnings;
use Data:

umper;
my @stuff = ([qw/foo bar baz bam boom/],[qw/foo bar wizz wham whallop/]);
my %h;
my $ref = \%h;
foreach my $stuff_ref (@stuff) {
for my $level (@$stuff_ref) {
if (exists $ref->{$level}) { # If the key exists then just move on
$ref = $ref->{$level};
next;
}
$ref->{$level} = {};
$ref = $ref->{$level};
}
$ref = \%h; # Start at the beginning again
}
print Dumper(\%h);
Which seems to work OK. I probably kludged up your beautiful code -
please accept my humble apologies if this is the case.
# ./hashes.pl
$VAR1 = {
'foo' => {
'bar' => {
'baz' => {
'bam' => {
'boom' => {}
}
},
'wizz' => {
'wham' => {
'whallop' => {}
}
}
}
}
};
Cheers,
Allan.