Debian Codegraph @

upstream/debian-unstable/man3/Hash::Util::FieldHash.3perl

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "Hash::Util::FieldHash 3perl"
58 .TH Hash::Util::FieldHash 3perl 2025-11-16 "perl v5.40.1" "Perl Programmers Reference Guide"
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 Hash::Util::FieldHash \- Support for Inside\-Out Classes
65 .SH SYNOPSIS
66 .IX Header "SYNOPSIS"
67 .Vb 2
68 \& ### Create fieldhashes
69 \& use Hash::Util qw(fieldhash fieldhashes);
70 \&
71 \& # Create a single field hash
72 \& fieldhash my %foo;
73 \&
74 \& # Create three at once...
75 \& fieldhashes \e my(%foo, %bar, %baz);
76 \& # ...or any number
77 \& fieldhashes @hashrefs;
78 \&
79 \& ### Create an idhash and register it for garbage collection
80 \& use Hash::Util::FieldHash qw(idhash register);
81 \& idhash my %name;
82 \& my $object = \e do { my $o };
83 \& # register the idhash for garbage collection with $object
84 \& register($object, \e %name);
85 \& # the following entry will be deleted when $object goes out of scope
86 \& $name{$object} = \*(AqJohn Doe\*(Aq;
87 \&
88 \& ### Register an ordinary hash for garbage collection
89 \& use Hash::Util::FieldHash qw(id register);
90 \& my %name;
91 \& my $object = \e do { my $o };
92 \& # register the hash %name for garbage collection of $object\*(Aqs id
93 \& register $object, \e %name;
94 \& # the following entry will be deleted when $object goes out of scope
95 \& $name{id $object} = \*(AqJohn Doe\*(Aq;
96 .Ve
97 .SH FUNCTIONS
98 .IX Header "FUNCTIONS"
99 \&\f(CW\*(C`Hash::Util::FieldHash\*(C'\fR offers a number of functions in support of
100 "The Inside-out Technique" of class construction.
101 .IP id 4
102 .IX Item "id"
103 .Vb 1
104 \& id($obj)
105 .Ve
106 .Sp
107 Returns the reference address of a reference \f(CW$obj\fR. If \f(CW$obj\fR is
108 not a reference, returns \f(CW$obj\fR.
109 .Sp
110 This function is a stand-in replacement for
111 Scalar::Util::refaddr,
112 that is, it returns
113 the reference address of its argument as a numeric value. The only
114 difference is that \f(CWrefaddr()\fR returns \f(CW\*(C`undef\*(C'\fR when given a
115 non-reference while \f(CWid()\fR returns its argument unchanged.
116 .Sp
117 \&\f(CWid()\fR also uses a caching technique that makes it faster when
118 the id of an object is requested often, but slower if it is needed
119 only once or twice.
120 .IP id_2obj 4
121 .IX Item "id_2obj"
122 .Vb 1
123 \& $obj = id_2obj($id)
124 .Ve
125 .Sp
126 If \f(CW$id\fR is the id of a registered object (see "register"), returns
127 the object, otherwise an undefined value. For registered objects this
128 is the inverse function of \f(CWid()\fR.
129 .IP register 4
130 .IX Item "register"
131 .Vb 2
132 \& register($obj)
133 \& register($obj, @hashrefs)
134 .Ve
135 .Sp
136 In the first form, registers an object to work with for the function
137 \&\f(CWid_2obj()\fR. In the second form, it additionally marks the given
138 hashrefs down for garbage collection. This means that when the object
139 goes out of scope, any entries in the given hashes under the key of
140 \&\f(CWid($obj)\fR will be deleted from the hashes.
141 .Sp
142 It is a fatal error to register a non-reference \f(CW$obj\fR. Any non-hashrefs
143 among the following arguments are silently ignored.
144 .Sp
145 It is \fInot\fR an error to register the same object multiple times with
146 varying sets of hashrefs. Any hashrefs that are not registered yet
147 will be added, others ignored.
148 .Sp
149 Registry also implies thread support. When a new thread is created,
150 all references are replaced with new ones, including all objects.
151 If a hash uses the reference address of an object as a key, that
152 connection would be broken. With a registered object, its id will
153 be updated in all hashes registered with it.
154 .IP idhash 4
155 .IX Item "idhash"
156 .Vb 1
157 \& idhash my %hash
158 .Ve
159 .Sp
160 Makes an idhash from the argument, which must be a hash.
161 .Sp
162 An \fIidhash\fR works like a normal hash, except that it stringifies a
163 \&\fIreference used as a key\fR differently. A reference is stringified
164 as if the \f(CWid()\fR function had been invoked on it, that is, its
165 reference address in decimal is used as the key.
166 .IP idhashes 4
167 .IX Item "idhashes"
168 .Vb 2
169 \& idhashes \e my(%hash, %gnash, %trash)
170 \& idhashes \e @hashrefs
171 .Ve
172 .Sp
173 Creates many idhashes from its hashref arguments. Returns those
174 arguments that could be converted or their number in scalar context.
175 .IP fieldhash 4
176 .IX Item "fieldhash"
177 .Vb 1
178 \& fieldhash %hash;
179 .Ve
180 .Sp
181 Creates a single fieldhash. The argument must be a hash. Returns
182 a reference to the given hash if successful, otherwise nothing.
183 .Sp
184 A \fIfieldhash\fR is, in short, an idhash with auto-registry. When an
185 object (or, indeed, any reference) is used as a fieldhash key, the
186 fieldhash is automatically registered for garbage collection with
187 the object, as if \f(CW\*(C`register $obj, \e %fieldhash\*(C'\fR had been called.
188 .IP fieldhashes 4
189 .IX Item "fieldhashes"
190 .Vb 1
191 \& fieldhashes @hashrefs;
192 .Ve
193 .Sp
194 Creates any number of field hashes. Arguments must be hash references.
195 Returns the converted hashrefs in list context, their number in scalar
196 context.
197 .SH DESCRIPTION
198 .IX Header "DESCRIPTION"
199 A word on terminology: I shall use the term \fIfield\fR for a scalar
200 piece of data that a class associates with an object. Other terms that
201 have been used for this concept are "object variable", "(object) property",
202 "(object) attribute" and more. Especially "attribute" has some currency
203 among Perl programmer, but that clashes with the \f(CW\*(C`attributes\*(C'\fR pragma. The
204 term "field" also has some currency in this sense and doesn't seem
205 to conflict with other Perl terminology.
206 .PP
207 In Perl, an object is a blessed reference. The standard way of associating
208 data with an object is to store the data inside the object's body, that is,
209 the piece of data pointed to by the reference.
210 .PP
211 In consequence, if two or more classes want to access an object they
212 \&\fImust\fR agree on the type of reference and also on the organization of
213 data within the object body. Failure to agree on the type results in
214 immediate death when the wrong method tries to access an object. Failure
215 to agree on data organization may lead to one class trampling over the
216 data of another.
217 .PP
218 This object model leads to a tight coupling between subclasses.
219 If one class wants to inherit from another (and both classes access
220 object data), the classes must agree about implementation details.
221 Inheritance can only be used among classes that are maintained together,
222 in a single source or not.
223 .PP
224 In particular, it is not possible to write general-purpose classes
225 in this technique, classes that can advertise themselves as "Put me
226 on your \f(CW@ISA\fR list and use my methods". If the other class has different
227 ideas about how the object body is used, there is trouble.
228 .PP
229 For reference \f(CW\*(C`Name_hash\*(C'\fR in "Example 1" shows the standard implementation of
230 a simple class \f(CW\*(C`Name\*(C'\fR in the well-known hash based way. It also demonstrates
231 the predictable failure to construct a common subclass \f(CW\*(C`NamedFile\*(C'\fR
232 of \f(CW\*(C`Name\*(C'\fR and the class \f(CW\*(C`IO::File\*(C'\fR (whose objects \fImust\fR be globrefs).
233 .PP
234 Thus, techniques are of interest that store object data \fInot\fR in
235 the object body but some other place.
236 .SS "The Inside-out Technique"
237 .IX Subsection "The Inside-out Technique"
238 With \fIinside-out\fR classes, each class declares a (typically lexical)
239 hash for each field it wants to use. The reference address of an
240 object is used as the hash key. By definition, the reference address
241 is unique to each object so this guarantees a place for each field that
242 is private to the class and unique to each object. See \f(CW\*(C`Name_id\*(C'\fR
243 in "Example 1" for a simple example.
244 .PP
245 In comparison to the standard implementation where the object is a
246 hash and the fields correspond to hash keys, here the fields correspond
247 to hashes, and the object determines the hash key. Thus the hashes
248 appear to be turned \fIinside out\fR.
249 .PP
250 The body of an object is never examined by an inside-out class, only
251 its reference address is used. This allows for the body of an actual
252 object to be \fIanything at all\fR while the object methods of the class
253 still work as designed. This is a key feature of inside-out classes.
254 .SS "Problems of Inside-out"
255 .IX Subsection "Problems of Inside-out"
256 Inside-out classes give us freedom of inheritance, but as usual there
257 is a price.
258 .PP
259 Most obviously, there is the necessity of retrieving the reference
260 address of an object for each data access. It's a minor inconvenience,
261 but it does clutter the code.
262 .PP
263 More important (and less obvious) is the necessity of garbage
264 collection. When a normal object dies, anything stored in the
265 object body is garbage-collected by perl. With inside-out objects,
266 Perl knows nothing about the data stored in field hashes by a class,
267 but these must be deleted when the object goes out of scope. Thus
268 the class must provide a \f(CW\*(C`DESTROY\*(C'\fR method to take care of that.
269 .PP
270 In the presence of multiple classes it can be non-trivial
271 to make sure that every relevant destructor is called for
272 every object. Perl calls the first one it finds on the
273 inheritance tree (if any) and that's it.
274 .PP
275 A related issue is thread-safety. When a new thread is created,
276 the Perl interpreter is cloned, which implies that all reference
277 addresses in use will be replaced with new ones. Thus, if a class
278 tries to access a field of a cloned object its (cloned) data will
279 still be stored under the now invalid reference address of the
280 original in the parent thread. A general \f(CW\*(C`CLONE\*(C'\fR method must
281 be provided to re-establish the association.
282 .SS Solutions
283 .IX Subsection "Solutions"
284 \&\f(CW\*(C`Hash::Util::FieldHash\*(C'\fR addresses these issues on several
285 levels.
286 .PP
287 The \f(CWid()\fR function is provided in addition to the
288 existing \f(CWScalar::Util::refaddr()\fR. Besides its short name
289 it can be a little faster under some circumstances (and a
290 bit slower under others). Benchmark if it matters. The
291 working of \f(CWid()\fR also allows the use of the class name
292 as a \fIgeneric object\fR as described further down.
293 .PP
294 The \f(CWid()\fR function is incorporated in \fIid hashes\fR in the sense
295 that it is called automatically on every key that is used with
296 the hash. No explicit call is necessary.
297 .PP
298 The problems of garbage collection and thread safety are both
299 addressed by the function \f(CWregister()\fR. It registers an object
300 together with any number of hashes. Registry means that when the
301 object dies, an entry in any of the hashes under the reference
302 address of this object will be deleted. This guarantees garbage
303 collection in these hashes. It also means that on thread
304 cloning the object's entries in registered hashes will be
305 replaced with updated entries whose key is the cloned object's
306 reference address. Thus the object-data association becomes
307 thread-safe.
308 .PP
309 Object registry is best done when the object is initialized
310 for use with a class. That way, garbage collection and thread
311 safety are established for every object and every field that is
312 initialized.
313 .PP
314 Finally, \fIfield hashes\fR incorporate all these functions in one
315 package. Besides automatically calling the \f(CWid()\fR function
316 on every object used as a key, the object is registered with
317 the field hash on first use. Classes based on field hashes
318 are fully garbage-collected and thread safe without further
319 measures.
320 .SS "More Problems"
321 .IX Subsection "More Problems"
322 Another problem that occurs with inside-out classes is serialization.
323 Since the object data is not in its usual place, standard routines
324 like \f(CWStorable::freeze()\fR, \f(CWStorable::thaw()\fR and
325 \&\f(CWData::Dumper::Dumper()\fR can't deal with it on their own. Both
326 \&\f(CW\*(C`Data::Dumper\*(C'\fR and \f(CW\*(C`Storable\*(C'\fR provide the necessary hooks to
327 make things work, but the functions or methods used by the hooks
328 must be provided by each inside-out class.
329 .PP
330 A general solution to the serialization problem would require another
331 level of registry, one that associates \fIclasses\fR and fields.
332 So far, the functions of \f(CW\*(C`Hash::Util::FieldHash\*(C'\fR are unaware of
333 any classes, which I consider a feature. Therefore \f(CW\*(C`Hash::Util::FieldHash\*(C'\fR
334 doesn't address the serialization problems.
335 .SS "The Generic Object"
336 .IX Subsection "The Generic Object"
337 Classes based on the \f(CWid()\fR function (and hence classes based on
338 \&\f(CWidhash()\fR and \f(CWfieldhash()\fR) show a peculiar behavior in that
339 the class name can be used like an object. Specifically, methods
340 that set or read data associated with an object continue to work as
341 class methods, just as if the class name were an object, distinct from
342 all other objects, with its own data. This object may be called
343 the \fIgeneric object\fR of the class.
344 .PP
345 This works because field hashes respond to keys that are not references
346 like a normal hash would and use the string offered as the hash key.
347 Thus, if a method is called as a class method, the field hash is presented
348 with the class name instead of an object and blithely uses it as a key.
349 Since the keys of real objects are decimal numbers, there is no
350 conflict and the slot in the field hash can be used like any other.
351 The \f(CWid()\fR function behaves correspondingly with respect to non-reference
352 arguments.
353 .PP
354 Two possible uses (besides ignoring the property) come to mind.
355 A singleton class could be implemented this using the generic object.
356 If necessary, an \f(CWinit()\fR method could die or ignore calls with
357 actual objects (references), so only the generic object will ever exist.
358 .PP
359 Another use of the generic object would be as a template. It is
360 a convenient place to store class-specific defaults for various
361 fields to be used in actual object initialization.
362 .PP
363 Usually, the feature can be entirely ignored. Calling \fIobject
364 methods\fR as \fIclass methods\fR normally leads to an error and isn't used
365 routinely anywhere. It may be a problem that this error isn't
366 indicated by a class with a generic object.
367 .SS "How to use Field Hashes"
368 .IX Subsection "How to use Field Hashes"
369 Traditionally, the definition of an inside-out class contains a bare
370 block inside which a number of lexical hashes are declared and the
371 basic accessor methods defined, usually through \f(CW\*(C`Scalar::Util::refaddr\*(C'\fR.
372 Further methods may be defined outside this block. There has to be
373 a DESTROY method and, for thread support, a CLONE method.
374 .PP
375 When field hashes are used, the basic structure remains the same.
376 Each lexical hash will be made a field hash. The call to \f(CW\*(C`refaddr\*(C'\fR
377 can be omitted from the accessor methods. DESTROY and CLONE methods
378 are not necessary.
379 .PP
380 If you have an existing inside-out class, simply making all hashes
381 field hashes with no other change should make no difference. Through
382 the calls to \f(CW\*(C`refaddr\*(C'\fR or equivalent, the field hashes never get to
383 see a reference and work like normal hashes. Your DESTROY (and
384 CLONE) methods are still needed.
385 .PP
386 To make the field hashes kick in, it is easiest to redefine \f(CW\*(C`refaddr\*(C'\fR
387 as
388 .PP
389 .Vb 1
390 \& sub refaddr { shift }
391 .Ve
392 .PP
393 instead of importing it from \f(CW\*(C`Scalar::Util\*(C'\fR. It should now be possible
394 to disable DESTROY and CLONE. Note that while it isn't disabled,
395 DESTROY will be called before the garbage collection of field hashes,
396 so it will be invoked with a functional object and will continue to
397 function.
398 .PP
399 It is not desirable to import the functions \f(CW\*(C`fieldhash\*(C'\fR and/or
400 \&\f(CW\*(C`fieldhashes\*(C'\fR into every class that is going to use them. They
401 are only used once to set up the class. When the class is up and running,
402 these functions serve no more purpose.
403 .PP
404 If there are only a few field hashes to declare, it is simplest to
405 .PP
406 .Vb 1
407 \& use Hash::Util::FieldHash;
408 .Ve
409 .PP
410 early and call the functions qualified:
411 .PP
412 .Vb 1
413 \& Hash::Util::FieldHash::fieldhash my %foo;
414 .Ve
415 .PP
416 Otherwise, import the functions into a convenient package like
417 \&\f(CW\*(C`HUF\*(C'\fR or, more general, \f(CW\*(C`Aux\*(C'\fR
418 .PP
419 .Vb 4
420 \& {
421 \& package Aux;
422 \& use Hash::Util::FieldHash \*(Aq:all\*(Aq;
423 \& }
424 .Ve
425 .PP
426 and call
427 .PP
428 .Vb 1
429 \& Aux::fieldhash my %foo;
430 .Ve
431 .PP
432 as needed.
433 .SS "Garbage-Collected Hashes"
434 .IX Subsection "Garbage-Collected Hashes"
435 Garbage collection in a field hash means that entries will "spontaneously"
436 disappear when the object that created them disappears. That must be
437 borne in mind, especially when looping over a field hash. If anything
438 you do inside the loop could cause an object to go out of scope, a
439 random key may be deleted from the hash you are looping over. That
440 can throw the loop iterator, so it's best to cache a consistent snapshot
441 of the keys and/or values and loop over that. You will still have to
442 check that a cached entry still exists when you get to it.
443 .PP
444 Garbage collection can be confusing when keys are created in a field hash
445 from normal scalars as well as references. Once a reference is \fIused\fR with
446 a field hash, the entry will be collected, even if it was later overwritten
447 with a plain scalar key (every positive integer is a candidate). This
448 is true even if the original entry was deleted in the meantime. In fact,
449 deletion from a field hash, and also a test for existence constitute
450 \&\fIuse\fR in this sense and create a liability to delete the entry when
451 the reference goes out of scope. If you happen to create an entry
452 with an identical key from a string or integer, that will be collected
453 instead. Thus, mixed use of references and plain scalars as field hash
454 keys is not entirely supported.
455 .SH EXAMPLES
456 .IX Header "EXAMPLES"
457 The examples show a very simple class that implements a \fIname\fR, consisting
458 of a first and last name (no middle initial). The name class has four
459 methods:
460 .IP \(bu 4
461 \&\f(CWinit()\fR
462 .Sp
463 An object method that initializes the first and last name to its
464 two arguments. If called as a class method, \f(CWinit()\fR creates an
465 object in the given class and initializes that.
466 .IP \(bu 4
467 \&\f(CWfirst()\fR
468 .Sp
469 Retrieve the first name
470 .IP \(bu 4
471 \&\f(CWlast()\fR
472 .Sp
473 Retrieve the last name
474 .IP \(bu 4
475 \&\f(CWname()\fR
476 .Sp
477 Retrieve the full name, the first and last name joined by a blank.
478 .PP
479 The examples show this class implemented with different levels of
480 support by \f(CW\*(C`Hash::Util::FieldHash\*(C'\fR. All supported combinations
481 are shown. The difference between implementations is often quite
482 small. The implementations are:
483 .IP \(bu 4
484 \&\f(CW\*(C`Name_hash\*(C'\fR
485 .Sp
486 A conventional (not inside-out) implementation where an object is
487 a hash that stores the field values, without support by
488 \&\f(CW\*(C`Hash::Util::FieldHash\*(C'\fR. This implementation doesn't allow
489 arbitrary inheritance.
490 .IP \(bu 4
491 \&\f(CW\*(C`Name_id\*(C'\fR
492 .Sp
493 Inside-out implementation based on the \f(CWid()\fR function. It needs
494 a \f(CW\*(C`DESTROY\*(C'\fR method. For thread support a \f(CW\*(C`CLONE\*(C'\fR method (not shown)
495 would also be needed. Instead of \f(CWHash::Util::FieldHash::id()\fR the
496 function \f(CW\*(C`Scalar::Util::refaddr\*(C'\fR could be used with very little
497 functional difference. This is the basic pattern of an inside-out
498 class.
499 .IP \(bu 4
500 \&\f(CW\*(C`Name_idhash\*(C'\fR
501 .Sp
502 Idhash-based inside-out implementation. Like \f(CW\*(C`Name_id\*(C'\fR it needs
503 a \f(CW\*(C`DESTROY\*(C'\fR method and would need \f(CW\*(C`CLONE\*(C'\fR for thread support.
504 .IP \(bu 4
505 \&\f(CW\*(C`Name_id_reg\*(C'\fR
506 .Sp
507 Inside-out implementation based on the \f(CWid()\fR function with explicit
508 object registry. No destructor is needed and objects are thread safe.
509 .IP \(bu 4
510 \&\f(CW\*(C`Name_idhash_reg\*(C'\fR
511 .Sp
512 Idhash-based inside-out implementation with explicit object registry.
513 No destructor is needed and objects are thread safe.
514 .IP \(bu 4
515 \&\f(CW\*(C`Name_fieldhash\*(C'\fR
516 .Sp
517 FieldHash-based inside-out implementation. Object registry happens
518 automatically. No destructor is needed and objects are thread safe.
519 .PP
520 These examples are realized in the code below, which could be copied
521 to a file \fIExample.pm\fR.
522 .SS "Example 1"
523 .IX Subsection "Example 1"
524 .Vb 1
525 \& use strict; use warnings;
526 \&
527 \& {
528 \& package Name_hash; # standard implementation: the
529 \& # object is a hash
530 \& sub init {
531 \& my $obj = shift;
532 \& my ($first, $last) = @_;
533 \& # create an object if called as class method
534 \& $obj = bless {}, $obj unless ref $obj;
535 \& $obj\->{ first} = $first;
536 \& $obj\->{ last} = $last;
537 \& $obj;
538 \& }
539 \&
540 \& sub first { shift()\->{ first} }
541 \& sub last { shift()\->{ last} }
542 \&
543 \& sub name {
544 \& my $n = shift;
545 \& join \*(Aq \*(Aq => $n\->first, $n\->last;
546 \& }
547 \&
548 \& }
549 \&
550 \& {
551 \& package Name_id;
552 \& use Hash::Util::FieldHash qw(id);
553 \&
554 \& my (%first, %last);
555 \&
556 \& sub init {
557 \& my $obj = shift;
558 \& my ($first, $last) = @_;
559 \& # create an object if called as class method
560 \& $obj = bless \e my $o, $obj unless ref $obj;
561 \& $first{ id $obj} = $first;
562 \& $last{ id $obj} = $last;
563 \& $obj;
564 \& }
565 \&
566 \& sub first { $first{ id shift()} }
567 \& sub last { $last{ id shift()} }
568 \&
569 \& sub name {
570 \& my $n = shift;
571 \& join \*(Aq \*(Aq => $n\->first, $n\->last;
572 \& }
573 \&
574 \& sub DESTROY {
575 \& my $id = id shift;
576 \& delete $first{ $id};
577 \& delete $last{ $id};
578 \& }
579 \&
580 \& }
581 \&
582 \& {
583 \& package Name_idhash;
584 \& use Hash::Util::FieldHash;
585 \&
586 \& Hash::Util::FieldHash::idhashes( \e my (%first, %last) );
587 \&
588 \& sub init {
589 \& my $obj = shift;
590 \& my ($first, $last) = @_;
591 \& # create an object if called as class method
592 \& $obj = bless \e my $o, $obj unless ref $obj;
593 \& $first{ $obj} = $first;
594 \& $last{ $obj} = $last;
595 \& $obj;
596 \& }
597 \&
598 \& sub first { $first{ shift()} }
599 \& sub last { $last{ shift()} }
600 \&
601 \& sub name {
602 \& my $n = shift;
603 \& join \*(Aq \*(Aq => $n\->first, $n\->last;
604 \& }
605 \&
606 \& sub DESTROY {
607 \& my $n = shift;
608 \& delete $first{ $n};
609 \& delete $last{ $n};
610 \& }
611 \&
612 \& }
613 \&
614 \& {
615 \& package Name_id_reg;
616 \& use Hash::Util::FieldHash qw(id register);
617 \&
618 \& my (%first, %last);
619 \&
620 \& sub init {
621 \& my $obj = shift;
622 \& my ($first, $last) = @_;
623 \& # create an object if called as class method
624 \& $obj = bless \e my $o, $obj unless ref $obj;
625 \& register( $obj, \e (%first, %last) );
626 \& $first{ id $obj} = $first;
627 \& $last{ id $obj} = $last;
628 \& $obj;
629 \& }
630 \&
631 \& sub first { $first{ id shift()} }
632 \& sub last { $last{ id shift()} }
633 \&
634 \& sub name {
635 \& my $n = shift;
636 \& join \*(Aq \*(Aq => $n\->first, $n\->last;
637 \& }
638 \& }
639 \&
640 \& {
641 \& package Name_idhash_reg;
642 \& use Hash::Util::FieldHash qw(register);
643 \&
644 \& Hash::Util::FieldHash::idhashes \e my (%first, %last);
645 \&
646 \& sub init {
647 \& my $obj = shift;
648 \& my ($first, $last) = @_;
649 \& # create an object if called as class method
650 \& $obj = bless \e my $o, $obj unless ref $obj;
651 \& register( $obj, \e (%first, %last) );
652 \& $first{ $obj} = $first;
653 \& $last{ $obj} = $last;
654 \& $obj;
655 \& }
656 \&
657 \& sub first { $first{ shift()} }
658 \& sub last { $last{ shift()} }
659 \&
660 \& sub name {
661 \& my $n = shift;
662 \& join \*(Aq \*(Aq => $n\->first, $n\->last;
663 \& }
664 \& }
665 \&
666 \& {
667 \& package Name_fieldhash;
668 \& use Hash::Util::FieldHash;
669 \&
670 \& Hash::Util::FieldHash::fieldhashes \e my (%first, %last);
671 \&
672 \& sub init {
673 \& my $obj = shift;
674 \& my ($first, $last) = @_;
675 \& # create an object if called as class method
676 \& $obj = bless \e my $o, $obj unless ref $obj;
677 \& $first{ $obj} = $first;
678 \& $last{ $obj} = $last;
679 \& $obj;
680 \& }
681 \&
682 \& sub first { $first{ shift()} }
683 \& sub last { $last{ shift()} }
684 \&
685 \& sub name {
686 \& my $n = shift;
687 \& join \*(Aq \*(Aq => $n\->first, $n\->last;
688 \& }
689 \& }
690 \&
691 \& 1;
692 .Ve
693 .PP
694 To exercise the various implementations the script below can
695 be used.
696 .PP
697 It sets up a class \f(CW\*(C`Name\*(C'\fR that is a mirror of one of the implementation
698 classes \f(CW\*(C`Name_hash\*(C'\fR, \f(CW\*(C`Name_id\*(C'\fR, ..., \f(CW\*(C`Name_fieldhash\*(C'\fR. That determines
699 which implementation is run.
700 .PP
701 The script first verifies the function of the \f(CW\*(C`Name\*(C'\fR class.
702 .PP
703 In the second step, the free inheritability of the implementation
704 (or lack thereof) is demonstrated. For this purpose it constructs
705 a class called \f(CW\*(C`NamedFile\*(C'\fR which is a common subclass of \f(CW\*(C`Name\*(C'\fR and
706 the standard class \f(CW\*(C`IO::File\*(C'\fR. This puts inheritability to the test
707 because objects of \f(CW\*(C`IO::File\*(C'\fR \fImust\fR be globrefs. Objects of \f(CW\*(C`NamedFile\*(C'\fR
708 should behave like a file opened for reading and also support the \f(CWname()\fR
709 method. This class juncture works with exception of the \f(CW\*(C`Name_hash\*(C'\fR
710 implementation, where object initialization fails because of the
711 incompatibility of object bodies.
712 .SS "Example 2"
713 .IX Subsection "Example 2"
714 .Vb 1
715 \& use strict; use warnings; $| = 1;
716 \&
717 \& use Example;
718 \&
719 \& {
720 \& package Name;
721 \& use parent \*(AqName_id\*(Aq; # define here which implementation to run
722 \& }
723 \&
724 \&
725 \& # Verify that the base package works
726 \& my $n = Name\->init(qw(Albert Einstein));
727 \& print $n\->name, "\en";
728 \& print "\en";
729 \&
730 \& # Create a named file handle (See definition below)
731 \& my $nf = NamedFile\->init(qw(/tmp/x Filomena File));
732 \& # use as a file handle...
733 \& for ( 1 .. 3 ) {
734 \& my $l = <$nf>;
735 \& print "line $_: $l";
736 \& }
737 \& # ...and as a Name object
738 \& print "...brought to you by ", $nf\->name, "\en";
739 \& exit;
740 \&
741 \&
742 \& # Definition of NamedFile
743 \& package NamedFile;
744 \& use parent \*(AqName\*(Aq;
745 \& use parent \*(AqIO::File\*(Aq;
746 \&
747 \& sub init {
748 \& my $obj = shift;
749 \& my ($file, $first, $last) = @_;
750 \& $obj = $obj\->IO::File::new() unless ref $obj;
751 \& $obj\->open($file) or die "Can\*(Aqt read \*(Aq$file\*(Aq: $!";
752 \& $obj\->Name::init($first, $last);
753 \& }
754 \& _\|_END_\|_
755 .Ve
756 .SH GUTS
757 .IX Header "GUTS"
758 To make \f(CW\*(C`Hash::Util::FieldHash\*(C'\fR work, there were two changes to
759 \&\fIperl\fR itself. \f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR was made available for hashes,
760 and weak references now call uvar \f(CW\*(C`get\*(C'\fR magic after a weakref has been
761 cleared. The first feature is used to make field hashes intercept
762 their keys upon access. The second one triggers garbage collection.
763 .ie n .SS "The ""PERL_MAGIC_uvar"" interface for hashes"
764 .el .SS "The \f(CWPERL_MAGIC_uvar\fP interface for hashes"
765 .IX Subsection "The PERL_MAGIC_uvar interface for hashes"
766 \&\f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR \fIget\fR magic is called from \f(CW\*(C`hv_fetch_common\*(C'\fR and
767 \&\f(CW\*(C`hv_delete_common\*(C'\fR through the function \f(CW\*(C`hv_magic_uvar_xkey\*(C'\fR, which
768 defines the interface. The call happens for hashes with "uvar" magic
769 if the \f(CW\*(C`ufuncs\*(C'\fR structure has equal values in the \f(CW\*(C`uf_val\*(C'\fR and \f(CW\*(C`uf_set\*(C'\fR
770 fields. Hashes are unaffected if (and as long as) these fields
771 hold different values.
772 .PP
773 Upon the call, the \f(CW\*(C`mg_obj\*(C'\fR field will hold the hash key to be accessed.
774 Upon return, the \f(CW\*(C`SV*\*(C'\fR value in \f(CW\*(C`mg_obj\*(C'\fR will be used in place of the
775 original key in the hash access. The integer index value in the first
776 parameter will be the \f(CW\*(C`action\*(C'\fR value from \f(CW\*(C`hv_fetch_common\*(C'\fR, or \-1
777 if the call is from \f(CW\*(C`hv_delete_common\*(C'\fR.
778 .PP
779 This is a template for a function suitable for the \f(CW\*(C`uf_val\*(C'\fR field in
780 a \f(CW\*(C`ufuncs\*(C'\fR structure for this call. The \f(CW\*(C`uf_set\*(C'\fR and \f(CW\*(C`uf_index\*(C'\fR
781 fields are irrelevant.
782 .PP
783 .Vb 10
784 \& IV watch_key(pTHX_ IV action, SV* field) {
785 \& MAGIC* mg = mg_find(field, PERL_MAGIC_uvar);
786 \& SV* keysv = mg\->mg_obj;
787 \& /* Do whatever you need to. If you decide to
788 \& supply a different key newkey, return it like this
789 \& */
790 \& sv_2mortal(newkey);
791 \& mg\->mg_obj = newkey;
792 \& return 0;
793 \& }
794 .Ve
795 .SS "Weakrefs call uvar magic"
796 .IX Subsection "Weakrefs call uvar magic"
797 When a weak reference is stored in an \f(CW\*(C`SV\*(C'\fR that has "uvar" magic, \f(CW\*(C`set\*(C'\fR
798 magic is called after the reference has gone stale. This hook can be
799 used to trigger further garbage-collection activities associated with
800 the referenced object.
801 .SS "How field hashes work"
802 .IX Subsection "How field hashes work"
803 The three features of key hashes, \fIkey replacement\fR, \fIthread support\fR,
804 and \fIgarbage collection\fR are supported by a data structure called
805 the \fIobject registry\fR. This is a private hash where every object
806 is stored. An "object" in this sense is any reference (blessed or
807 unblessed) that has been used as a field hash key.
808 .PP
809 The object registry keeps track of references that have been used as
810 field hash keys. The keys are generated from the reference address
811 like in a field hash (though the registry isn't a field hash). Each
812 value is a weak copy of the original reference, stored in an \f(CW\*(C`SV\*(C'\fR that
813 is itself magical (\f(CW\*(C`PERL_MAGIC_uvar\*(C'\fR again). The magical structure
814 holds a list (another hash, really) of field hashes that the reference
815 has been used with. When the weakref becomes stale, the magic is
816 activated and uses the list to delete the reference from all field
817 hashes it has been used with. After that, the entry is removed from
818 the object registry itself. Implicitly, that frees the magic structure
819 and the storage it has been using.
820 .PP
821 Whenever a reference is used as a field hash key, the object registry
822 is checked and a new entry is made if necessary. The field hash is
823 then added to the list of fields this reference has used.
824 .PP
825 The object registry is also used to repair a field hash after thread
826 cloning. Here, the entire object registry is processed. For every
827 reference found there, the field hashes it has used are visited and
828 the entry is updated.
829 .SS "Internal function Hash::Util::FieldHash::_fieldhash"
830 .IX Subsection "Internal function Hash::Util::FieldHash::_fieldhash"
831 .Vb 2
832 \& # test if %hash is a field hash
833 \& my $result = _fieldhash \e %hash, 0;
834 \&
835 \& # make %hash a field hash
836 \& my $result = _fieldhash \e %hash, 1;
837 .Ve
838 .PP
839 \&\f(CW\*(C`_fieldhash\*(C'\fR is the internal function used to create field hashes.
840 It takes two arguments, a hashref and a mode. If the mode is boolean
841 false, the hash is not changed but tested if it is a field hash. If
842 the hash isn't a field hash the return value is boolean false. If it
843 is, the return value indicates the mode of field hash. When called with
844 a boolean true mode, it turns the given hash into a field hash of this
845 mode, returning the mode of the created field hash. \f(CW\*(C`_fieldhash\*(C'\fR
846 does not erase the given hash.
847 .PP
848 Currently there is only one type of field hash, and only the boolean
849 value of the mode makes a difference, but that may change.
850 .SH AUTHOR
851 .IX Header "AUTHOR"
852 Anno Siegel (ANNO) wrote the xs code and the changes in perl proper
853 Jerry Hedden (JDHEDDEN) made it faster
854 .SH "COPYRIGHT AND LICENSE"
855 .IX Header "COPYRIGHT AND LICENSE"
856 Copyright (C) 2006\-2007 by (Anno Siegel)
857 .PP
858 This library is free software; you can redistribute it and/or modify
859 it under the same terms as Perl itself, either Perl version 5.8.7 or,
860 at your option, any later version of Perl 5 you may have available.