donfreenut has asked for the wisdom of the Perl Monks concerning the following question:


I have a hash of hashes. It looks like this:
my %servers = ( BOUVET => { ps3_path => '\\\\BOUVET\\resin-2.0.3\\doc\\ps3\\', resin_path => '\\\\BOUVET\\resin-2.0.3\\', contexts_path => '\\\\BOUVET\\resin-2.0.3\\doc\\ps3\\contexts\ +\', customizations => { some_key => 'some data', another_key => 'more data' } } );
I want to get at all the key/value pairs in the customizations hash. I'm trying this:
foreach my $customization (keys $servers{BOUVET}{customizations}) { print "$customization\n"; }
and Perl is telling me that:

Type of arg 1 to keys must be hash (not hash element) at C:\deployment\newscripts\deploy-internal.pl line 102, near "}) "

which isn't cool. Do I have to somehow tell the keys function that $servers{BOUVET}{customizations} is itself a hash?

Muchas gracias...

---
donfreenut

Replies are listed 'Best First'.
Re: Do I have to explicitly tell keys() that the hash in my hash of hashes is a hash?
by runrig (Abbot) on Dec 07, 2001 at 23:48 UTC
    In short, the answer is 'yes':
    foreach my $customization (keys %{$servers{BOUVET}{customizations}}) {
    The long answer, and recommended reading, is perldoc perlref, perldsc, perllol, and perlreftut (the last one comes with 5.6 so is not on this site).
Re: Do I have to explicitly tell keys() that the hash in my hash of hashes is a hash?
by lestrrat (Deacon) on Dec 07, 2001 at 23:49 UTC
    %servers <- that's a hash $servers{ BOUVET } <- that's a ref to a hash $server{ BOUVET }{ customizations } <- that's another ref to a hash

    keys() expets a hash as its value, not a ref to a hash. so you need to dereference it:

    keys %{ $server{ BOUVET }{ customizations } }
Re: Do I have to explicitly tell keys() that the hash in my hash of hashes is a hash?
by dragonchild (Archbishop) on Dec 07, 2001 at 23:48 UTC
    Try doing something like:
    foreach my $customization (keys %{$serverse{BOUVET}{customizations}}) +{
    You have a hashref, so you need to tell Perl to dereference the hashref.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: Do I have to explicitly tell keys() that the hash in my hash of hashes is a hash?
by demerphq (Chancellor) on Dec 07, 2001 at 23:51 UTC
    Yes you do need to explicitly tell keys its a hash. Annoying at times, but necessary.
    use strict; use warnings; my $hash={a=>{b=>1},c=>{d=>1}}; foreach my $key (keys %$hash) { print "$key\n"; foreach my $subkey (keys %{$hash->{$key}}) { print "\t$subkey\n"; } }
    So theres the simple way and the complicated way...

    HTH

    Yves / DeMerphq
    --
    This space for rent.