Debian Codegraph @

upstream/mageia-cauldron/man3pm/Hash::Util::FieldHash.3pm

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