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

You get to see a piece of perl code which (condensed) reads:

my $v; # ... $v = $hash{$foo}->{$bar}; # ... some lines later the same location # has to be retrieved to check for changes # to the multilevel hash $ref = [ $foo, $bar ]; my $nv = $hash{$ref}; if ($v eq $nv) { ...

and you are told that this just works. Can it? does it? how so?

First thing you do is to look after %hash. For tied hashes, the keys are not stringified before being passed on to the underlying methods. They are passed "as is" - scalar or list. It is the task of the FETCH etc. methods to handle that as well as the context in which they are called. Are there any other possibilities except tied hashes where the code presented above could work?

Replies are listed 'Best First'.
Re: reference as key to hash
by ikegami (Patriarch) on Apr 24, 2009 at 01:54 UTC

    To present the interface of a hash while not actually being a hash requires a feature called "magic". tie is a specific form of this magic, but not the only one. For example, %ENV is magical, but isn't tied.

    It's possible to overload hash dereference, but I don't see how that would help here even if you were using a hash reference and not a hash.

    So what's the real question?

      No real question here, only a mildly interesting puzzle. I recently realized that stringification of hash keys is true only for perl builtin hashes, not for tied hashes, and found the disguise as a SoPW appropriate for sharing the finding...

Re: reference as key to hash
by spx2 (Deacon) on Apr 24, 2009 at 15:09 UTC
    why would you use a reference as a key to a hash ? references are ephemeral in many ways , what if you want to itertate over them later, when other items have taken the references that the old ones had when you made the hash ? I think this is not a very good idea.

      why would you use a reference as a key to a hash ?

      You may have noticed the reference wasn't used as the key, just as a means of passing a more complex key.

      references are ephemeral in many ways

      So is anything you program or do. But while in scope you are present.