Sandra Schlichting
Sandra Schlichting

Reputation: 25986

How to insert hash of hashs in hash?

I would like to start with an empty hash, and then insert hash of hashes of the same kind into the hash.

#!/usr/bin/perl

use strict;
use warnings;

my %h = {};

$h{"1"} => {
    a => -1,
    b => -1,
    c => [
    {
        d => -1,
        e => -1,
    },
    ],
};

However this gives

Useless use of hash element in void context at ./hash.pl line 8.
Useless use of anonymous hash ({}) in void context at ./hash.pl line 8.
Reference found where even-sized list expected at ./hash.pl line 6.

It is sort of a database I would like to make, where I can insert the delete structures of the $h{"1"} kind.

Any ideas how to do this?

Upvotes: 3

Views: 1434

Answers (2)

Arindam Paul
Arindam Paul

Reputation: 388

NOTE: References are always scalar as they contain address (kind of to think neatly)

When you create a nested data structure just remember that in perl we don't have to worry about how the space is allocated, how much space is allocated. It's pretty neat to handle anonymous storage of it's own.

But, Always remember the thumb rules for creating such storage like this,

To create an anonymous array, use square brackets instead of parentheses:

$ra = [ ];

To create an anonymous hash, use braces instead of square brackets:

$rh = { };

And that's all there is.

Now, What you wrote was something like this,

my %h={};

You are essentially creating a hash and initializing it with a reference which is a scalar.

That's why your program complained about this,

Just remove that line and rewrite your code like this,

#!/usr/bin/perl

use strict;
use warnings;

my $h={"1" => {
            a => -1,
            b => -1,
            c => [
                 {
                   d => -1,
                   e => -1,
                 },
                 ],
              }
};

Perl will take care of the rest.. Enjoy Perl :) :)

Upvotes: 3

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

To initialize a hash you use %h = ().
{} is a reference to an empty anonymous hash. Try this:

my %h = ();

$h{"1"} = {
    a => -1,
    b => -1,
    c => [{
        d => -1,
        e => -1,
    }],
};

Upvotes: 9

Related Questions