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

Hi all!

Hope you can help me out. I'v got an object which is a blessed ref to a hash, in which I would like to store a hash (or a ref to it).

So, this gives me something like

return bless(\{hash => \{}}, $class);
Now, how do I access an element in the inner hash?

Glad for all help!

Edit kudra, 2002-04-19 Added HTML plus codetag

Replies are listed 'Best First'.
Re: In a dereference nightmare!
by Juerd (Abbot) on Apr 18, 2002 at 08:01 UTC

    bless(\{hash => \{}}, $class);

    That blesses a reference to a reference to a hash that contains a single value that is a reference to a reference of a hash.

    The { } hashref construct creates a hash reference for you, so there is no need to put a backslash in front of it. That will only create a reference to the newly created reference to an anonymous hash.

    Without the backslashes:

    bless { hash => {} }, $class; ... $object->{hash}->{key_inside_that};
    The arrow between two sets of braces is optional, and it's not the only notation. Here are a few alternatives (less good, imho):
    $object->{hash}{key_inside_that}, $$object{hash}{key_inside_that}, ${${$object}{hash}}{key_inside_that}
    If you don't remove the backslashes, you will have scalar references, and those can only be dereferenced with the ugly syntax:
    bless \{ hash => \{} }, $class; ... ${$$object->{hash}}->{key_inside_that}; ${${${$object}}{hash}}{key_inside_that}; # etcetera...
    Read perlref for more information.

    HTH

    - Yes, I reinvent wheels.
    - Spam: Visit eurotraQ.
    

      Thank you very much! This answered my question perfectly!
Re: In a dereference nightmare!
by Biker (Priest) on Apr 18, 2002 at 07:59 UTC

    In a design nightmare? ;-)

    I'd recommend that you do not return a reference to the inner hash to the caller that instantiates your object.

    Return the reference to your blessed hash as for any usual implementation of a class. Then access the values of your blessed hash, that is "the inner hash" and any other object properties, only via the methods you provide to the caller.


    Everything went worng, just as foreseen.

Re: In a dereference nightmare!
by Fletch (Bishop) on Apr 18, 2002 at 07:54 UTC

    \{hash => \{}} is a reference to a reference to a hash. This probably isn't what you want (i.e. you now have a reference to a scalar which contains a reference to a hash). {} is the anonymous hash ref constructor, there's no need to use \ to take a reference. Read perldoc perlreftut and perldoc perlref a bit more.