SPUG:object in a hash

Colin Meyer cmeyer at helvella.org
Wed Jun 4 13:26:33 CDT 2003


On Wed, Jun 04, 2003 at 11:04:50AM -0700, ced at carios2.ca.boeing.com wrote:
> Hash keys always get stringified and this morphing breaks
> the original object reference. There's probably an alternative 
> (and better structure) you could use that'd avoid storing 
> object ref's as hash keys. 
> 
> However, FreezeThaw is a possibility if you're stuck:
> 
>   use FreezeThaw qw( freeze thaw );
> 
>   $INFOHASH{ freeze( my $obj = new Foo ) }++;
>   ...
> 
>   foreach my $key ( keys %INFOHASH) {
>      my( $obj ) = thaw( $key );
>      ... 
>   }

Or if you don't feel like writing any extra freeze() and thaw()'s, use
Tie::RefHash, which does all that for you. From the perldoc:

DESCRIPTION
       This module provides the ability to use references as hash keys if you
       first "tie" the hash variable to this module.  Normally, only the keys
       of the tied hash itself are preserved as references; to use references
       as keys in hashes-of-hashes, use Tie::RefHash::Nestable, included as
       part of Tie::RefHash.

[...]


Have fun,
-Colin.




More information about the spug-list mailing list