7 Tie::RefHash - use references as hash keys
13 tie HASHVARIABLE, 'Tie::RefHash', LIST;
14 tie HASHVARIABLE, 'Tie::RefHash::Nestable', LIST;
20 This module provides the ability to use references as hash keys if you
21 first C<tie> the hash variable to this module. Normally, only the
22 keys of the tied hash itself are preserved as references; to use
23 references as keys in hashes-of-hashes, use Tie::RefHash::Nestable,
24 included as part of Tie::RefHash.
26 It is implemented using the standard perl TIEHASH interface. Please
27 see the C<tie> entry in perlfunc(1) and perltie(1) for more information.
29 The Nestable version works by looking for hash references being stored
30 and converting them to tied hashes so that they too can have
31 references as keys. This will happen without warning whenever you
32 store a reference to one of your own hashes in the tied hash.
37 tie %h, 'Tie::RefHash';
43 %h = ($a => 1, $b => 2, $c => 3, $d => 4, $e => 5);
50 tie %h, 'Tie::RefHash::Nestable';
52 for (keys %h, keys %{$h{$a}}) {
58 Gurusamy Sarathy gsar@activestate.com
60 'Nestable' by Ed Avis ed@membled.com
64 perl(1), perlfunc(1), perltie(1)
75 my $usethreads = $Config::Config{usethreads}; # && exists $INC{"threads.pm"}
76 *_HAS_THREADS = $usethreads ? sub () { 1 } : sub () { 0 };
77 require Scalar::Util if $usethreads; # we need weaken()
80 require overload; # to support objects with overloaded ""
82 my (@thread_object_registry, $count); # used by the CLONE method to rehash the keys after their refaddr changed
89 $s->STORE(shift, shift);
93 # remember the object so that we can rekey it on CLONE
94 push @thread_object_registry, $s;
95 # but make this a weak reference, so that there are no leaks
96 Scalar::Util::weaken( $thread_object_registry[-1] );
98 if ( ++$count > 1000 ) {
99 # this ensures we don't fill up with a huge array dead weakrefs
100 @thread_object_registry = grep { defined } @thread_object_registry;
110 # when the thread has been cloned all the objects need to be updated.
111 # dead weakrefs are undefined, so we filter them out
112 @thread_object_registry = grep { defined && do { $_->CLONE_OBJ; 1 } } @thread_object_registry;
113 $count = 0; # we just cleaned up
118 # rehash all the ref keys based on their new StrVal
119 %{ $self->[0] } = map { overload::StrVal($_->[0]) => $_ } values %{ $self->[0] };
125 my $kstr = overload::StrVal($k);
126 if (defined $s->[0]{$kstr}) {
141 $s->[0]{overload::StrVal($k)} = [$k, $v];
152 ? (delete($s->[0]{overload::StrVal($k)}) || [])->[1]
153 : delete($s->[1]{$k});
158 (ref $k) ? exists($s->[0]{overload::StrVal($k)}) : exists($s->[1]{$k});
163 keys %{$s->[0]}; # reset iterator
164 keys %{$s->[1]}; # reset iterator
165 $s->[2] = 0; # flag for iteration, see NEXTKEY
173 if (($k, $v) = each %{$s->[0]}) {
180 return each %{$s->[1]};
190 package Tie::RefHash::Nestable;
192 @ISA = 'Tie::RefHash';
196 if (ref($v) eq 'HASH' and not tied %$v) {
198 tie %$v, ref($s), @elems;
200 $s->SUPER::STORE($k, $v);