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

Hi guys,

I'm having some troubles to insert a hash into a hash?

This is a similar code:
#global hash list example my %hashList = {}; #second global hash my %secondHash = ( car => "NULL", bike => "NULL", cat => "NULL", etc => "NULL", ); #inside procedure "add" $hashList->{$count} = %secondHash;
Then I try to print it:
my %hashtemp = $hashList->{$count}; while ( my ($key, $value) = each(%hashtemp) ) { print "\n$key => $value\n"; }
And I get a bad output: "9/16 => "

Is this supposed to work? What is wrong in my code?

Thanks!!

Replies are listed 'Best First'.
Re: Insert a new key (that is a hash) to a hash
by jettero (Monsignor) on Jun 17, 2009 at 17:55 UTC
    You can only store scalars in a hash. So you'll need to store a reference to the hash (\%hashname) rather than the hash itself. Otherwise you'll end up storing the scalarization of the hash instead. See perldata, perlref and perllol for detailed info on this.

    I'm a pretty hardcore Perl nerd and I still re-read those every year or so. They're written quite well.

    -Paul

Re: Insert a new key (that is a hash) to a hash
by Transient (Hermit) on Jun 17, 2009 at 17:58 UTC
    You're mixing up hash references with hashes in your syntax. The 9/16 is you hash in a scalar context, not the hash itself.

    You want something more like:
    my %hashList = (); ... $hashList{$count} = \%secondHash; ... my $hashtemp = $hashList{$count}; while ( my ($key, $value) = each ( %$hashtemp ) ) { ... }
Re: Insert a new key (that is a hash) to a hash
by kennethk (Abbot) on Jun 17, 2009 at 18:01 UTC
    Let me expound upon what jettero has written:

    A hash consists of a series of scalar to scalar mappings. When you assign a hash to the scalar $hashList->{$count}, Perl detects you are using the hash in scalar context, and hence returns the hash's bucket information. If you really want to generate a nested structure, you need to use hash references, not hashes, a.k.a. $hashList->{$count} = \%secondHash; See perllol, perlref and perlreftut for more info.

Re: Insert a new key (that is a hash) to a hash
by GrandFather (Saint) on Jun 17, 2009 at 22:55 UTC

    Always use strictures (use strict; use warnings; - see The strictures, according to Seuss)! Your sample code fails in at least two different ways under strictures, both of which would have alerted you to errors that are the root of your problem.

    my %hashList = {};

    Generates the warning: "Reference found where even-sized list expected at ..."

    $hashList->{$count} = %secondHash;

    Generates the error: "Global symbol "$hashList" requires explicit package name at ..."


    True laziness is hard work