Debian Codegraph @

upstream/mageia-cauldron/man1/perltie.1

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 "PERLTIE 1"
61 .TH PERLTIE 1 2025-06-24 "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 perltie \- how to hide an object class in a simple variable
68 .IX Xref "tie"
69 .SH SYNOPSIS
70 .IX Header "SYNOPSIS"
71 .Vb 1
72 \& tie VARIABLE, CLASSNAME, LIST
73 \&
74 \& $object = tied VARIABLE
75 \&
76 \& untie VARIABLE
77 .Ve
78 .SH DESCRIPTION
79 .IX Header "DESCRIPTION"
80 Prior to release 5.0 of Perl, a programmer could use \fBdbmopen()\fR
81 to connect an on\-disk database in the standard Unix \fBdbm\fR\|(3x)
82 format magically to a \f(CW%HASH\fR in their program. However, their Perl was either
83 built with one particular dbm library or another, but not both, and
84 you couldn\*(Aqt extend this mechanism to other packages or types of variables.
85 .PP
86 Now you can.
87 .PP
88 The \fBtie()\fR function binds a variable to a class (package) that will provide
89 the implementation for access methods for that variable. Once this magic
90 has been performed, accessing a tied variable automatically triggers
91 method calls in the proper class. The complexity of the class is
92 hidden behind magic methods calls. The method names are in ALL CAPS,
93 which is a convention that Perl uses to indicate that they\*(Aqre called
94 implicitly rather than explicitly\-\-just like the \fBBEGIN()\fR and \fBEND()\fR
95 functions.
96 .PP
97 In the \fBtie()\fR call, \f(CW\*(C`VARIABLE\*(C'\fR is the name of the variable to be
98 enchanted. \f(CW\*(C`CLASSNAME\*(C'\fR is the name of a class implementing objects of
99 the correct type. Any additional arguments in the \f(CW\*(C`LIST\*(C'\fR are passed to
100 the appropriate constructor method for that class\-\-meaning \fBTIESCALAR()\fR,
101 \&\fBTIEARRAY()\fR, \fBTIEHASH()\fR, or \fBTIEHANDLE()\fR. (Typically these are arguments
102 such as might be passed to the \fBdbminit()\fR function of C.) The object
103 returned by the "new" method is also returned by the \fBtie()\fR function,
104 which would be useful if you wanted to access other methods in
105 \&\f(CW\*(C`CLASSNAME\*(C'\fR. (You don\*(Aqt actually have to return a reference to a right
106 "type" (e.g., HASH or \f(CW\*(C`CLASSNAME\*(C'\fR) so long as it\*(Aqs a properly blessed
107 object.) You can also retrieve a reference to the underlying object
108 using the \fBtied()\fR function.
109 .PP
110 Unlike \fBdbmopen()\fR, the \fBtie()\fR function will not \f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR a module
111 for you\-\-you need to do that explicitly yourself.
112 .SS "Tying Scalars"
113 .IX Xref "scalar, tying"
114 .IX Subsection "Tying Scalars"
115 A class implementing a tied scalar should define the following methods:
116 TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
117 .PP
118 Let\*(Aqs look at each in turn, using as an example a tie class for
119 scalars that allows the user to do something like:
120 .PP
121 .Vb 2
122 \& tie $his_speed, \*(AqNice\*(Aq, getppid();
123 \& tie $my_speed, \*(AqNice\*(Aq, $$;
124 .Ve
125 .PP
126 And now whenever either of those variables is accessed, its current
127 system priority is retrieved and returned. If those variables are set,
128 then the process\*(Aqs priority is changed!
129 .PP
130 We\*(Aqll use Jarkko Hietaniemi <\[email protected]\fR>\*(Aqs BSD::Resource class (not
131 included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
132 from your system, as well as the \fBgetpriority()\fR and \fBsetpriority()\fR system
133 calls. Here\*(Aqs the preamble of the class.
134 .PP
135 .Vb 5
136 \& package Nice;
137 \& use Carp;
138 \& use BSD::Resource;
139 \& use strict;
140 \& $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
141 .Ve
142 .IP "TIESCALAR classname, LIST" 4
143 .IX Xref "TIESCALAR"
144 .IX Item "TIESCALAR classname, LIST"
145 This is the constructor for the class. That means it is
146 expected to return a blessed reference to a new scalar
147 (probably anonymous) that it\*(Aqs creating. For example:
148 .Sp
149 .Vb 3
150 \& sub TIESCALAR {
151 \& my $class = shift;
152 \& my $pid = shift || $$; # 0 means me
153 \&
154 \& if ($pid !~ /^\ed+$/) {
155 \& carp "Nice::Tie::Scalar got non\-numeric pid $pid" if $^W;
156 \& return undef;
157 \& }
158 \&
159 \& unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
160 \& carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
161 \& return undef;
162 \& }
163 \&
164 \& return bless \e$pid, $class;
165 \& }
166 .Ve
167 .Sp
168 This tie class has chosen to return an error rather than raising an
169 exception if its constructor should fail. While this is how \fBdbmopen()\fR works,
170 other classes may well not wish to be so forgiving. It checks the global
171 variable \f(CW$^W\fR to see whether to emit a bit of noise anyway.
172 .IP "FETCH this" 4
173 .IX Xref "FETCH"
174 .IX Item "FETCH this"
175 This method will be triggered every time the tied variable is accessed
176 (read). It takes no arguments beyond its self reference, which is the
177 object representing the scalar we\*(Aqre dealing with. Because in this case
178 we\*(Aqre using just a SCALAR ref for the tied scalar object, a simple $$self
179 allows the method to get at the real value stored there. In our example
180 below, that real value is the process ID to which we\*(Aqve tied our variable.
181 .Sp
182 .Vb 10
183 \& sub FETCH {
184 \& my $self = shift;
185 \& confess "wrong type" unless ref $self;
186 \& croak "usage error" if @_;
187 \& my $nicety;
188 \& local($!) = 0;
189 \& $nicety = getpriority(PRIO_PROCESS, $$self);
190 \& if ($!) { croak "getpriority failed: $!" }
191 \& return $nicety;
192 \& }
193 .Ve
194 .Sp
195 This time we\*(Aqve decided to blow up (raise an exception) if the renice
196 fails\-\-there\*(Aqs no place for us to return an error otherwise, and it\*(Aqs
197 probably the right thing to do.
198 .IP "STORE this, value" 4
199 .IX Xref "STORE"
200 .IX Item "STORE this, value"
201 This method will be triggered every time the tied variable is set
202 (assigned). Beyond its self reference, it also expects one (and only one)
203 argument: the new value the user is trying to assign. Don\*(Aqt worry about
204 returning a value from STORE; the semantic of assignment returning the
205 assigned value is implemented with FETCH.
206 .Sp
207 .Vb 5
208 \& sub STORE {
209 \& my $self = shift;
210 \& confess "wrong type" unless ref $self;
211 \& my $new_nicety = shift;
212 \& croak "usage error" if @_;
213 \&
214 \& if ($new_nicety < PRIO_MIN) {
215 \& carp sprintf
216 \& "WARNING: priority %d less than minimum system priority %d",
217 \& $new_nicety, PRIO_MIN if $^W;
218 \& $new_nicety = PRIO_MIN;
219 \& }
220 \&
221 \& if ($new_nicety > PRIO_MAX) {
222 \& carp sprintf
223 \& "WARNING: priority %d greater than maximum system priority %d",
224 \& $new_nicety, PRIO_MAX if $^W;
225 \& $new_nicety = PRIO_MAX;
226 \& }
227 \&
228 \& unless (defined setpriority(PRIO_PROCESS,
229 \& $$self,
230 \& $new_nicety))
231 \& {
232 \& confess "setpriority failed: $!";
233 \& }
234 \& }
235 .Ve
236 .IP "UNTIE this" 4
237 .IX Xref "UNTIE"
238 .IX Item "UNTIE this"
239 This method will be triggered when the \f(CW\*(C`untie\*(C'\fR occurs. This can be useful
240 if the class needs to know when no further calls will be made. (Except DESTROY
241 of course.) See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below for more details.
242 .IP "DESTROY this" 4
243 .IX Xref "DESTROY"
244 .IX Item "DESTROY this"
245 This method will be triggered when the tied variable needs to be destructed.
246 As with other object classes, such a method is seldom necessary, because Perl
247 deallocates its moribund object\*(Aqs memory for you automatically\-\-this isn\*(Aqt
248 C++, you know. We\*(Aqll use a DESTROY method here for debugging purposes only.
249 .Sp
250 .Vb 5
251 \& sub DESTROY {
252 \& my $self = shift;
253 \& confess "wrong type" unless ref $self;
254 \& carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
255 \& }
256 .Ve
257 .PP
258 That\*(Aqs about all there is to it. Actually, it\*(Aqs more than all there
259 is to it, because we\*(Aqve done a few nice things here for the sake
260 of completeness, robustness, and general aesthetics. Simpler
261 TIESCALAR classes are certainly possible.
262 .SS "Tying Arrays"
263 .IX Xref "array, tying"
264 .IX Subsection "Tying Arrays"
265 A class implementing a tied ordinary array should define the following
266 methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE, CLEAR
267 and perhaps UNTIE and/or DESTROY.
268 .PP
269 FETCHSIZE and STORESIZE are used to provide \f(CW$#array\fR and
270 equivalent \f(CWscalar(@array)\fR access.
271 .PP
272 The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are
273 required if the perl operator with the corresponding (but lowercase) name
274 is to operate on the tied array. The \fBTie::Array\fR class can be used as a
275 base class to implement the first five of these in terms of the basic
276 methods above. The default implementations of DELETE and EXISTS in
277 \&\fBTie::Array\fR simply \f(CW\*(C`croak\*(C'\fR.
278 .PP
279 In addition EXTEND will be called when perl would have pre\-extended
280 allocation in a real array.
281 .PP
282 For this discussion, we\*(Aqll implement an array whose elements are a fixed
283 size at creation. If you try to create an element larger than the fixed
284 size, you\*(Aqll take an exception. For example:
285 .PP
286 .Vb 4
287 \& use FixedElem_Array;
288 \& tie @array, \*(AqFixedElem_Array\*(Aq, 3;
289 \& $array[0] = \*(Aqcat\*(Aq; # ok.
290 \& $array[1] = \*(Aqdogs\*(Aq; # exception, length(\*(Aqdogs\*(Aq) > 3.
291 .Ve
292 .PP
293 The preamble code for the class is as follows:
294 .PP
295 .Vb 3
296 \& package FixedElem_Array;
297 \& use Carp;
298 \& use strict;
299 .Ve
300 .IP "TIEARRAY classname, LIST" 4
301 .IX Xref "TIEARRAY"
302 .IX Item "TIEARRAY classname, LIST"
303 This is the constructor for the class. That means it is expected to
304 return a blessed reference through which the new array (probably an
305 anonymous ARRAY ref) will be accessed.
306 .Sp
307 In our example, just to show you that you don\*(Aqt \fIreally\fR have to return an
308 ARRAY reference, we\*(Aqll choose a HASH reference to represent our object.
309 A HASH works out well as a generic record type: the \f(CW\*(C`{ELEMSIZE}\*(C'\fR field will
310 store the maximum element size allowed, and the \f(CW\*(C`{ARRAY}\*(C'\fR field will hold the
311 true ARRAY ref. If someone outside the class tries to dereference the
312 object returned (doubtless thinking it is an ARRAY ref), they\*(Aqll blow up.
313 This just goes to show you that you should respect an object\*(Aqs privacy.
314 .Sp
315 .Vb 11
316 \& sub TIEARRAY {
317 \& my $class = shift;
318 \& my $elemsize = shift;
319 \& if ( @_ || $elemsize =~ /\eD/ ) {
320 \& croak "usage: tie ARRAY, \*(Aq" . _\|_PACKAGE_\|_ . "\*(Aq, elem_size";
321 \& }
322 \& return bless {
323 \& ELEMSIZE => $elemsize,
324 \& ARRAY => [],
325 \& }, $class;
326 \& }
327 .Ve
328 .IP "FETCH this, index" 4
329 .IX Xref "FETCH"
330 .IX Item "FETCH this, index"
331 This method will be triggered every time an individual element the tied array
332 is accessed (read). It takes one argument beyond its self reference: the
333 index whose value we\*(Aqre trying to fetch.
334 .Sp
335 .Vb 5
336 \& sub FETCH {
337 \& my $self = shift;
338 \& my $index = shift;
339 \& return $self\->{ARRAY}\->[$index];
340 \& }
341 .Ve
342 .Sp
343 If a negative array index is used to read from an array, the index
344 will be translated to a positive one internally by calling FETCHSIZE
345 before being passed to FETCH. You may disable this feature by
346 assigning a true value to the variable \f(CW$NEGATIVE_INDICES\fR in the
347 tied array class.
348 .Sp
349 As you may have noticed, the name of the FETCH method (et al.) is the same
350 for all accesses, even though the constructors differ in names (TIESCALAR
351 vs TIEARRAY). While in theory you could have the same class servicing
352 several tied types, in practice this becomes cumbersome, and it\*(Aqs easiest
353 to keep them at simply one tie type per class.
354 .IP "STORE this, index, value" 4
355 .IX Xref "STORE"
356 .IX Item "STORE this, index, value"
357 This method will be triggered every time an element in the tied array is set
358 (written). It takes two arguments beyond its self reference: the index at
359 which we\*(Aqre trying to store something and the value we\*(Aqre trying to put
360 there.
361 .Sp
362 In our example, \f(CW\*(C`undef\*(C'\fR is really \f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR number of
363 spaces so we have a little more work to do here:
364 .Sp
365 .Vb 11
366 \& sub STORE {
367 \& my $self = shift;
368 \& my( $index, $value ) = @_;
369 \& if ( length $value > $self\->{ELEMSIZE} ) {
370 \& croak "length of $value is greater than $self\->{ELEMSIZE}";
371 \& }
372 \& # fill in the blanks
373 \& $self\->STORESIZE( $index ) if $index > $self\->FETCHSIZE();
374 \& # right justify to keep element size for smaller elements
375 \& $self\->{ARRAY}\->[$index] = sprintf "%$self\->{ELEMSIZE}s", $value;
376 \& }
377 .Ve
378 .Sp
379 Negative indexes are treated the same as with FETCH.
380 .IP "FETCHSIZE this" 4
381 .IX Xref "FETCHSIZE"
382 .IX Item "FETCHSIZE this"
383 Returns the total number of items in the tied array associated with
384 object \fIthis\fR. (Equivalent to \f(CWscalar(@array)\fR). For example:
385 .Sp
386 .Vb 4
387 \& sub FETCHSIZE {
388 \& my $self = shift;
389 \& return scalar $self\->{ARRAY}\->@*;
390 \& }
391 .Ve
392 .IP "STORESIZE this, count" 4
393 .IX Xref "STORESIZE"
394 .IX Item "STORESIZE this, count"
395 Sets the total number of items in the tied array associated with
396 object \fIthis\fR to be \fIcount\fR. If this makes the array larger then
397 class\*(Aqs mapping of \f(CW\*(C`undef\*(C'\fR should be returned for new positions.
398 If the array becomes smaller then entries beyond count should be
399 deleted.
400 .Sp
401 In our example, \*(Aqundef\*(Aq is really an element containing
402 \&\f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR number of spaces. Observe:
403 .Sp
404 .Vb 10
405 \& sub STORESIZE {
406 \& my $self = shift;
407 \& my $count = shift;
408 \& if ( $count > $self\->FETCHSIZE() ) {
409 \& foreach ( $count \- $self\->FETCHSIZE() .. $count ) {
410 \& $self\->STORE( $_, \*(Aq\*(Aq );
411 \& }
412 \& } elsif ( $count < $self\->FETCHSIZE() ) {
413 \& foreach ( 0 .. $self\->FETCHSIZE() \- $count \- 2 ) {
414 \& $self\->POP();
415 \& }
416 \& }
417 \& }
418 .Ve
419 .IP "EXTEND this, count" 4
420 .IX Xref "EXTEND"
421 .IX Item "EXTEND this, count"
422 Informative call that array is likely to grow to have \fIcount\fR entries.
423 Can be used to optimize allocation. This method need do nothing.
424 .Sp
425 In our example there is no reason to implement this method, so we leave
426 it as a no\-op. This method is only relevant to tied array implementations
427 where there is the possibility of having the allocated size of the array
428 be larger than is visible to a perl programmer inspecting the size of the
429 array. Many tied array implementations will have no reason to implement it.
430 .Sp
431 .Vb 5
432 \& sub EXTEND {
433 \& my $self = shift;
434 \& my $count = shift;
435 \& # nothing to see here, move along.
436 \& }
437 .Ve
438 .Sp
439 \&\fBNOTE:\fR It is generally an error to make this equivalent to STORESIZE.
440 Perl may from time to time call EXTEND without wanting to actually change
441 the array size directly. Any tied array should function correctly if this
442 method is a no\-op, even if perhaps they might not be as efficient as they
443 would if this method was implemented.
444 .IP "EXISTS this, key" 4
445 .IX Xref "EXISTS"
446 .IX Item "EXISTS this, key"
447 Verify that the element at index \fIkey\fR exists in the tied array \fIthis\fR.
448 .Sp
449 In our example, we will determine that if an element consists of
450 \&\f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR spaces only, it does not exist:
451 .Sp
452 .Vb 7
453 \& sub EXISTS {
454 \& my $self = shift;
455 \& my $index = shift;
456 \& return 0 if ! defined $self\->{ARRAY}\->[$index] ||
457 \& $self\->{ARRAY}\->[$index] eq \*(Aq \*(Aq x $self\->{ELEMSIZE};
458 \& return 1;
459 \& }
460 .Ve
461 .IP "DELETE this, key" 4
462 .IX Xref "DELETE"
463 .IX Item "DELETE this, key"
464 Delete the element at index \fIkey\fR from the tied array \fIthis\fR.
465 .Sp
466 In our example, a deleted item is \f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR spaces:
467 .Sp
468 .Vb 5
469 \& sub DELETE {
470 \& my $self = shift;
471 \& my $index = shift;
472 \& return $self\->STORE( $index, \*(Aq\*(Aq );
473 \& }
474 .Ve
475 .IP "CLEAR this" 4
476 .IX Xref "CLEAR"
477 .IX Item "CLEAR this"
478 Clear (remove, delete, ...) all values from the tied array associated with
479 object \fIthis\fR. For example:
480 .Sp
481 .Vb 4
482 \& sub CLEAR {
483 \& my $self = shift;
484 \& return $self\->{ARRAY} = [];
485 \& }
486 .Ve
487 .IP "PUSH this, LIST" 4
488 .IX Xref "PUSH"
489 .IX Item "PUSH this, LIST"
490 Append elements of \fILIST\fR to the array. For example:
491 .Sp
492 .Vb 7
493 \& sub PUSH {
494 \& my $self = shift;
495 \& my @list = @_;
496 \& my $last = $self\->FETCHSIZE();
497 \& $self\->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
498 \& return $self\->FETCHSIZE();
499 \& }
500 .Ve
501 .IP "POP this" 4
502 .IX Xref "POP"
503 .IX Item "POP this"
504 Remove last element of the array and return it. For example:
505 .Sp
506 .Vb 4
507 \& sub POP {
508 \& my $self = shift;
509 \& return pop $self\->{ARRAY}\->@*;
510 \& }
511 .Ve
512 .IP "SHIFT this" 4
513 .IX Xref "SHIFT"
514 .IX Item "SHIFT this"
515 Remove the first element of the array (shifting other elements down)
516 and return it. For example:
517 .Sp
518 .Vb 4
519 \& sub SHIFT {
520 \& my $self = shift;
521 \& return shift $self\->{ARRAY}\->@*;
522 \& }
523 .Ve
524 .IP "UNSHIFT this, LIST" 4
525 .IX Xref "UNSHIFT"
526 .IX Item "UNSHIFT this, LIST"
527 Insert LIST elements at the beginning of the array, moving existing elements
528 up to make room. For example:
529 .Sp
530 .Vb 9
531 \& sub UNSHIFT {
532 \& my $self = shift;
533 \& my @list = @_;
534 \& my $size = scalar( @list );
535 \& # make room for our list
536 \& $self\->{ARRAY}[ $size .. $self\->{ARRAY}\->$#* + $size ]\->@*
537 \& = $self\->{ARRAY}\->@*
538 \& $self\->STORE( $_, $list[$_] ) foreach 0 .. $#list;
539 \& }
540 .Ve
541 .IP "SPLICE this, offset, length, LIST" 4
542 .IX Xref "SPLICE"
543 .IX Item "SPLICE this, offset, length, LIST"
544 Perform the equivalent of \f(CW\*(C`splice\*(C'\fR on the array.
545 .Sp
546 \&\fIoffset\fR is optional and defaults to zero, negative values count back
547 from the end of the array.
548 .Sp
549 \&\fIlength\fR is optional and defaults to rest of the array.
550 .Sp
551 \&\fILIST\fR may be empty.
552 .Sp
553 Returns a list of the original \fIlength\fR elements at \fIoffset\fR.
554 .Sp
555 In our example, we\*(Aqll use a little shortcut if there is a \fILIST\fR:
556 .Sp
557 .Vb 11
558 \& sub SPLICE {
559 \& my $self = shift;
560 \& my $offset = shift || 0;
561 \& my $length = shift || $self\->FETCHSIZE() \- $offset;
562 \& my @list = ();
563 \& if ( @_ ) {
564 \& tie @list, _\|_PACKAGE_\|_, $self\->{ELEMSIZE};
565 \& @list = @_;
566 \& }
567 \& return splice $self\->{ARRAY}\->@*, $offset, $length, @list;
568 \& }
569 .Ve
570 .IP "UNTIE this" 4
571 .IX Xref "UNTIE"
572 .IX Item "UNTIE this"
573 Will be called when \f(CW\*(C`untie\*(C'\fR happens. (See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below.)
574 .IP "DESTROY this" 4
575 .IX Xref "DESTROY"
576 .IX Item "DESTROY this"
577 This method will be triggered when the tied variable needs to be destructed.
578 As with the scalar tie class, this is almost never needed in a
579 language that does its own garbage collection, so this time we\*(Aqll
580 just leave it out.
581 .SS "Tying Hashes"
582 .IX Xref "hash, tying"
583 .IX Subsection "Tying Hashes"
584 Hashes were the first Perl data type to be tied (see \fBdbmopen()\fR). A class
585 implementing a tied hash should define the following methods: TIEHASH is
586 the constructor. FETCH and STORE access the key and value pairs. EXISTS
587 reports whether a key is present in the hash, and DELETE deletes one.
588 CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY
589 and NEXTKEY implement the \fBkeys()\fR and \fBeach()\fR functions to iterate over all
590 the keys. SCALAR is triggered when the tied hash is evaluated in scalar
591 context, and in 5.28 onwards, by \f(CW\*(C`keys\*(C'\fR in boolean context. UNTIE is
592 called when \f(CW\*(C`untie\*(C'\fR happens, and DESTROY is called when the tied variable
593 is garbage collected.
594 .PP
595 If this seems like a lot, then feel free to inherit from merely the
596 standard Tie::StdHash module for most of your methods, redefining only the
597 interesting ones. See Tie::Hash for details.
598 .PP
599 Remember that Perl distinguishes between a key not existing in the hash,
600 and the key existing in the hash but having a corresponding value of
601 \&\f(CW\*(C`undef\*(C'\fR. The two possibilities can be tested with the \f(CWexists()\fR and
602 \&\f(CWdefined()\fR functions.
603 .PP
604 Here\*(Aqs an example of a somewhat interesting tied hash class: it gives you
605 a hash representing a particular user\*(Aqs dot files. You index into the hash
606 with the name of the file (minus the dot) and you get back that dot file\*(Aqs
607 contents. For example:
608 .PP
609 .Vb 8
610 \& use DotFiles;
611 \& tie %dot, \*(AqDotFiles\*(Aq;
612 \& if ( $dot{profile} =~ /MANPATH/ ||
613 \& $dot{login} =~ /MANPATH/ ||
614 \& $dot{cshrc} =~ /MANPATH/ )
615 \& {
616 \& print "you seem to set your MANPATH\en";
617 \& }
618 .Ve
619 .PP
620 Or here\*(Aqs another sample of using our tied class:
621 .PP
622 .Vb 5
623 \& tie %him, \*(AqDotFiles\*(Aq, \*(Aqdaemon\*(Aq;
624 \& foreach $f ( keys %him ) {
625 \& printf "daemon dot file %s is size %d\en",
626 \& $f, length $him{$f};
627 \& }
628 .Ve
629 .PP
630 In our tied hash DotFiles example, we use a regular
631 hash for the object containing several important
632 fields, of which only the \f(CW\*(C`{LIST}\*(C'\fR field will be what the
633 user thinks of as the real hash.
634 .IP USER 5
635 .IX Item "USER"
636 whose dot files this object represents
637 .IP HOME 5
638 .IX Item "HOME"
639 where those dot files live
640 .IP CLOBBER 5
641 .IX Item "CLOBBER"
642 whether we should try to change or remove those dot files
643 .IP LIST 5
644 .IX Item "LIST"
645 the hash of dot file names and content mappings
646 .PP
647 Here\*(Aqs the start of \fIDotfiles.pm\fR:
648 .PP
649 .Vb 5
650 \& package DotFiles;
651 \& use Carp;
652 \& sub whowasi { (caller(1))[3] . \*(Aq()\*(Aq }
653 \& my $DEBUG = 0;
654 \& sub debug { $DEBUG = @_ ? shift : 1 }
655 .Ve
656 .PP
657 For our example, we want to be able to emit debugging info to help in tracing
658 during development. We keep also one convenience function around
659 internally to help print out warnings; \fBwhowasi()\fR returns the function name
660 that calls it.
661 .PP
662 Here are the methods for the DotFiles tied hash.
663 .IP "TIEHASH classname, LIST" 4
664 .IX Xref "TIEHASH"
665 .IX Item "TIEHASH classname, LIST"
666 This is the constructor for the class. That means it is expected to
667 return a blessed reference through which the new object (probably but not
668 necessarily an anonymous hash) will be accessed.
669 .Sp
670 Here\*(Aqs the constructor:
671 .Sp
672 .Vb 9
673 \& sub TIEHASH {
674 \& my $class = shift;
675 \& my $user = shift || $>;
676 \& my $dotdir = shift || \*(Aq\*(Aq;
677 \& croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
678 \& $user = getpwuid($user) if $user =~ /^\ed+$/;
679 \& my $dir = (getpwnam($user))[7]
680 \& || croak "@{[&whowasi]}: no user $user";
681 \& $dir .= "/$dotdir" if $dotdir;
682 \&
683 \& my $node = {
684 \& USER => $user,
685 \& HOME => $dir,
686 \& LIST => {},
687 \& CLOBBER => 0,
688 \& };
689 \&
690 \& opendir(DIR, $dir)
691 \& || croak "@{[&whowasi]}: can\*(Aqt opendir $dir: $!";
692 \& foreach $dot ( grep /^\e./ && \-f "$dir/$_", readdir(DIR)) {
693 \& $dot =~ s/^\e.//;
694 \& $node\->{LIST}{$dot} = undef;
695 \& }
696 \& closedir DIR;
697 \& return bless $node, $class;
698 \& }
699 .Ve
700 .Sp
701 It\*(Aqs probably worth mentioning that if you\*(Aqre going to filetest the
702 return values out of a readdir, you\*(Aqd better prepend the directory
703 in question. Otherwise, because we didn\*(Aqt \fBchdir()\fR there, it would
704 have been testing the wrong file.
705 .IP "FETCH this, key" 4
706 .IX Xref "FETCH"
707 .IX Item "FETCH this, key"
708 This method will be triggered every time an element in the tied hash is
709 accessed (read). It takes one argument beyond its self reference: the key
710 whose value we\*(Aqre trying to fetch.
711 .Sp
712 Here\*(Aqs the fetch for our DotFiles example.
713 .Sp
714 .Vb 6
715 \& sub FETCH {
716 \& carp &whowasi if $DEBUG;
717 \& my $self = shift;
718 \& my $dot = shift;
719 \& my $dir = $self\->{HOME};
720 \& my $file = "$dir/.$dot";
721 \&
722 \& unless (exists $self\->{LIST}\->{$dot} || \-f $file) {
723 \& carp "@{[&whowasi]}: no $dot file" if $DEBUG;
724 \& return undef;
725 \& }
726 \&
727 \& if (defined $self\->{LIST}\->{$dot}) {
728 \& return $self\->{LIST}\->{$dot};
729 \& } else {
730 \& return $self\->{LIST}\->{$dot} = \`cat $dir/.$dot\`;
731 \& }
732 \& }
733 .Ve
734 .Sp
735 It was easy to write by having it call the Unix \fBcat\fR\|(1) command, but it
736 would probably be more portable to open the file manually (and somewhat
737 more efficient). Of course, because dot files are a Unixy concept, we\*(Aqre
738 not that concerned.
739 .IP "STORE this, key, value" 4
740 .IX Xref "STORE"
741 .IX Item "STORE this, key, value"
742 This method will be triggered every time an element in the tied hash is set
743 (written). It takes two arguments beyond its self reference: the index at
744 which we\*(Aqre trying to store something, and the value we\*(Aqre trying to put
745 there.
746 .Sp
747 Here in our DotFiles example, we\*(Aqll be careful not to let
748 them try to overwrite the file unless they\*(Aqve called the \fBclobber()\fR
749 method on the original object reference returned by \fBtie()\fR.
750 .Sp
751 .Vb 7
752 \& sub STORE {
753 \& carp &whowasi if $DEBUG;
754 \& my $self = shift;
755 \& my $dot = shift;
756 \& my $value = shift;
757 \& my $file = $self\->{HOME} . "/.$dot";
758 \& my $user = $self\->{USER};
759 \&
760 \& croak "@{[&whowasi]}: $file not clobberable"
761 \& unless $self\->{CLOBBER};
762 \&
763 \& open(my $f, \*(Aq>\*(Aq, $file) || croak "can\*(Aqt open $file: $!";
764 \& print $f $value;
765 \& close($f);
766 \& }
767 .Ve
768 .Sp
769 If they wanted to clobber something, they might say:
770 .Sp
771 .Vb 3
772 \& $ob = tie %daemon_dots, \*(Aqdaemon\*(Aq;
773 \& $ob\->clobber(1);
774 \& $daemon_dots{signature} = "A true daemon\en";
775 .Ve
776 .Sp
777 Another way to lay hands on a reference to the underlying object is to
778 use the \fBtied()\fR function, so they might alternately have set clobber
779 using:
780 .Sp
781 .Vb 2
782 \& tie %daemon_dots, \*(Aqdaemon\*(Aq;
783 \& tied(%daemon_dots)\->clobber(1);
784 .Ve
785 .Sp
786 The clobber method is simply:
787 .Sp
788 .Vb 4
789 \& sub clobber {
790 \& my $self = shift;
791 \& $self\->{CLOBBER} = @_ ? shift : 1;
792 \& }
793 .Ve
794 .IP "DELETE this, key" 4
795 .IX Xref "DELETE"
796 .IX Item "DELETE this, key"
797 This method is triggered when we remove an element from the hash,
798 typically by using the \fBdelete()\fR function. Again, we\*(Aqll
799 be careful to check whether they really want to clobber files.
800 .Sp
801 .Vb 2
802 \& sub DELETE {
803 \& carp &whowasi if $DEBUG;
804 \&
805 \& my $self = shift;
806 \& my $dot = shift;
807 \& my $file = $self\->{HOME} . "/.$dot";
808 \& croak "@{[&whowasi]}: won\*(Aqt remove file $file"
809 \& unless $self\->{CLOBBER};
810 \& delete $self\->{LIST}\->{$dot};
811 \& my $success = unlink($file);
812 \& carp "@{[&whowasi]}: can\*(Aqt unlink $file: $!" unless $success;
813 \& $success;
814 \& }
815 .Ve
816 .Sp
817 The value returned by DELETE becomes the return value of the call
818 to \fBdelete()\fR. If you want to emulate the normal behavior of \fBdelete()\fR,
819 you should return whatever FETCH would have returned for this key.
820 In this example, we have chosen instead to return a value which tells
821 the caller whether the file was successfully deleted.
822 .IP "CLEAR this" 4
823 .IX Xref "CLEAR"
824 .IX Item "CLEAR this"
825 This method is triggered when the whole hash is to be cleared, usually by
826 assigning the empty list to it.
827 .Sp
828 In our example, that would remove all the user\*(Aqs dot files! It\*(Aqs such a
829 dangerous thing that they\*(Aqll have to set CLOBBER to something higher than
830 1 to make it happen.
831 .Sp
832 .Vb 10
833 \& sub CLEAR {
834 \& carp &whowasi if $DEBUG;
835 \& my $self = shift;
836 \& croak "@{[&whowasi]}: won\*(Aqt remove all dot files for $self\->{USER}"
837 \& unless $self\->{CLOBBER} > 1;
838 \& my $dot;
839 \& foreach $dot ( keys $self\->{LIST}\->%* ) {
840 \& $self\->DELETE($dot);
841 \& }
842 \& }
843 .Ve
844 .IP "EXISTS this, key" 4
845 .IX Xref "EXISTS"
846 .IX Item "EXISTS this, key"
847 This method is triggered when the user uses the \fBexists()\fR function
848 on a particular hash. In our example, we\*(Aqll look at the \f(CW\*(C`{LIST}\*(C'\fR
849 hash element for this:
850 .Sp
851 .Vb 6
852 \& sub EXISTS {
853 \& carp &whowasi if $DEBUG;
854 \& my $self = shift;
855 \& my $dot = shift;
856 \& return exists $self\->{LIST}\->{$dot};
857 \& }
858 .Ve
859 .IP "FIRSTKEY this" 4
860 .IX Xref "FIRSTKEY"
861 .IX Item "FIRSTKEY this"
862 This method will be triggered when the user is going
863 to iterate through the hash, such as via a \fBkeys()\fR, \fBvalues()\fR, or \fBeach()\fR call.
864 .Sp
865 .Vb 6
866 \& sub FIRSTKEY {
867 \& carp &whowasi if $DEBUG;
868 \& my $self = shift;
869 \& my $x = keys $self\->{LIST}\->%*; # reset each() iterator
870 \& each $self\->{LIST}\->%*
871 \& }
872 .Ve
873 .Sp
874 FIRSTKEY is always called in scalar context and it should just
875 return the first key. \fBvalues()\fR, and \fBeach()\fR in list context,
876 will call FETCH for the returned keys.
877 .IP "NEXTKEY this, lastkey" 4
878 .IX Xref "NEXTKEY"
879 .IX Item "NEXTKEY this, lastkey"
880 This method gets triggered during a \fBkeys()\fR, \fBvalues()\fR, or \fBeach()\fR iteration. It has a
881 second argument which is the last key that had been accessed. This is
882 useful if you\*(Aqre caring about ordering or calling the iterator from more
883 than one sequence, or not really storing things in a hash anywhere.
884 .Sp
885 NEXTKEY is always called in scalar context and it should just
886 return the next key. \fBvalues()\fR, and \fBeach()\fR in list context,
887 will call FETCH for the returned keys.
888 .Sp
889 For our example, we\*(Aqre using a real hash so we\*(Aqll do just the simple
890 thing, but we\*(Aqll have to go through the LIST field indirectly.
891 .Sp
892 .Vb 5
893 \& sub NEXTKEY {
894 \& carp &whowasi if $DEBUG;
895 \& my $self = shift;
896 \& return each $self\->{LIST}\->%*
897 \& }
898 .Ve
899 .Sp
900 If the object underlying your tied hash isn\*(Aqt a real hash and you don\*(Aqt have
901 \&\f(CW\*(C`each\*(C'\fR available, then you should return \f(CW\*(C`undef\*(C'\fR or the empty list once you\*(Aqve
902 reached the end of your list of keys. See \f(CW\*(C`each\*(Aqs own documentation\*(C'\fR
903 for more details.
904 .IP "SCALAR this" 4
905 .IX Xref "SCALAR"
906 .IX Item "SCALAR this"
907 This is called when the hash is evaluated in scalar context, and in 5.28
908 onwards, by \f(CW\*(C`keys\*(C'\fR in boolean context. In order to mimic the behaviour of
909 untied hashes, this method must return a value which when used as boolean,
910 indicates whether the tied hash is considered empty. If this method does
911 not exist, perl will make some educated guesses and return true when
912 the hash is inside an iteration. If this isn\*(Aqt the case, FIRSTKEY is
913 called, and the result will be a false value if FIRSTKEY returns the empty
914 list, true otherwise.
915 .Sp
916 However, you should \fBnot\fR blindly rely on perl always doing the right
917 thing. Particularly, perl will mistakenly return true when you clear the
918 hash by repeatedly calling DELETE until it is empty. You are therefore
919 advised to supply your own SCALAR method when you want to be absolutely
920 sure that your hash behaves nicely in scalar context.
921 .Sp
922 In our example we can just call \f(CW\*(C`scalar\*(C'\fR on the underlying hash
923 referenced by \f(CW\*(C`$self\->{LIST}\*(C'\fR:
924 .Sp
925 .Vb 5
926 \& sub SCALAR {
927 \& carp &whowasi if $DEBUG;
928 \& my $self = shift;
929 \& return scalar $self\->{LIST}\->%*
930 \& }
931 .Ve
932 .Sp
933 NOTE: In perl 5.25 the behavior of scalar \f(CW%hash\fR on an untied hash changed
934 to return the count of keys. Prior to this it returned a string containing
935 information about the bucket setup of the hash. See
936 "bucket_ratio" in Hash::Util for a backwards compatibility path.
937 .IP "UNTIE this" 4
938 .IX Xref "UNTIE"
939 .IX Item "UNTIE this"
940 This is called when \f(CW\*(C`untie\*(C'\fR occurs. See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below.
941 .IP "DESTROY this" 4
942 .IX Xref "DESTROY"
943 .IX Item "DESTROY this"
944 This method is triggered when a tied hash is about to go out of
945 scope. You don\*(Aqt really need it unless you\*(Aqre trying to add debugging
946 or have auxiliary state to clean up. Here\*(Aqs a very simple function:
947 .Sp
948 .Vb 3
949 \& sub DESTROY {
950 \& carp &whowasi if $DEBUG;
951 \& }
952 .Ve
953 .PP
954 Note that functions such as \fBkeys()\fR and \fBvalues()\fR may return huge lists
955 when used on large objects, like DBM files. You may prefer to use the
956 \&\fBeach()\fR function to iterate over such. Example:
957 .PP
958 .Vb 7
959 \& # print out history file offsets
960 \& use NDBM_File;
961 \& tie(%HIST, \*(AqNDBM_File\*(Aq, \*(Aq/usr/lib/news/history\*(Aq, 1, 0);
962 \& while (($key,$val) = each %HIST) {
963 \& print $key, \*(Aq = \*(Aq, unpack(\*(AqL\*(Aq,$val), "\en";
964 \& }
965 \& untie(%HIST);
966 .Ve
967 .SS "Tying FileHandles"
968 .IX Xref "filehandle, tying"
969 .IX Subsection "Tying FileHandles"
970 This is partially implemented now.
971 .PP
972 A class implementing a tied filehandle should define the following
973 methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC,
974 READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE,
975 OPEN, EOF, FILENO, SEEK, TELL \- if the corresponding perl operators are
976 used on the handle.
977 .PP
978 When STDERR is tied, its PRINT method will be called to issue warnings
979 and error messages. This feature is temporarily disabled during the call,
980 which means you can use \f(CWwarn()\fR inside PRINT without starting a recursive
981 loop. And just like \f(CW\*(C`_\|_WARN_\|_\*(C'\fR and \f(CW\*(C`_\|_DIE_\|_\*(C'\fR handlers, STDERR\*(Aqs PRINT
982 method may be called to report parser errors, so the caveats mentioned under
983 "%SIG" in perlvar apply.
984 .PP
985 All of this is especially useful when perl is embedded in some other
986 program, where output to STDOUT and STDERR may have to be redirected
987 in some special way. See nvi and the Apache module for examples.
988 .PP
989 When tying a handle, the first argument to \f(CW\*(C`tie\*(C'\fR should begin with an
990 asterisk. So, if you are tying STDOUT, use \f(CW*STDOUT\fR. If you have
991 assigned it to a scalar variable, say \f(CW$handle\fR, use \f(CW*$handle\fR.
992 \&\f(CW\*(C`tie $handle\*(C'\fR ties the scalar variable \f(CW$handle\fR, not the handle inside
993 it.
994 .PP
995 In our example we\*(Aqre going to create a shouting handle.
996 .PP
997 .Vb 1
998 \& package Shout;
999 .Ve
1000 .IP "TIEHANDLE classname, LIST" 4
1001 .IX Xref "TIEHANDLE"
1002 .IX Item "TIEHANDLE classname, LIST"
1003 This is the constructor for the class. That means it is expected to
1004 return a blessed reference of some sort. The reference can be used to
1005 hold some internal information.
1006 .Sp
1007 .Vb 1
1008 \& sub TIEHANDLE { print "<shout>\en"; my $i; bless \e$i, shift }
1009 .Ve
1010 .IP "WRITE this, LIST" 4
1011 .IX Xref "WRITE"
1012 .IX Item "WRITE this, LIST"
1013 This method will be called when the handle is written to via the
1014 \&\f(CW\*(C`syswrite\*(C'\fR function.
1015 .Sp
1016 .Vb 5
1017 \& sub WRITE {
1018 \& $r = shift;
1019 \& my($buf,$len,$offset) = @_;
1020 \& print "WRITE called, \e$buf=$buf, \e$len=$len, \e$offset=$offset";
1021 \& }
1022 .Ve
1023 .IP "PRINT this, LIST" 4
1024 .IX Xref "PRINT"
1025 .IX Item "PRINT this, LIST"
1026 This method will be triggered every time the tied handle is printed to
1027 with the \f(CWprint()\fR or \f(CWsay()\fR functions. Beyond its self reference
1028 it also expects the list that was passed to the print function.
1029 .Sp
1030 .Vb 1
1031 \& sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\e }
1032 .Ve
1033 .Sp
1034 \&\f(CWsay()\fR acts just like \f(CWprint()\fR except $\e will be localized to \f(CW\*(C`\en\*(C'\fR so
1035 you need do nothing special to handle \f(CWsay()\fR in \f(CWPRINT()\fR.
1036 .IP "PRINTF this, LIST" 4
1037 .IX Xref "PRINTF"
1038 .IX Item "PRINTF this, LIST"
1039 This method will be triggered every time the tied handle is printed to
1040 with the \f(CWprintf()\fR function.
1041 Beyond its self reference it also expects the format and list that was
1042 passed to the printf function.
1043 .Sp
1044 .Vb 5
1045 \& sub PRINTF {
1046 \& shift;
1047 \& my $fmt = shift;
1048 \& print sprintf($fmt, @_);
1049 \& }
1050 .Ve
1051 .IP "READ this, LIST" 4
1052 .IX Xref "READ"
1053 .IX Item "READ this, LIST"
1054 This method will be called when the handle is read from via the \f(CW\*(C`read\*(C'\fR
1055 or \f(CW\*(C`sysread\*(C'\fR functions.
1056 .Sp
1057 .Vb 8
1058 \& sub READ {
1059 \& my $self = shift;
1060 \& my $bufref = \e$_[0];
1061 \& my(undef,$len,$offset) = @_;
1062 \& print "READ called, \e$buf=$bufref, \e$len=$len, \e$offset=$offset";
1063 \& # add to $$bufref, set $len to number of characters read
1064 \& $len;
1065 \& }
1066 .Ve
1067 .IP "READLINE this" 4
1068 .IX Xref "READLINE"
1069 .IX Item "READLINE this"
1070 This method is called when the handle is read via \f(CW\*(C`<HANDLE>\*(C'\fR
1071 or \f(CW\*(C`readline HANDLE\*(C'\fR.
1072 .Sp
1073 As per \f(CW\*(C`readline\*(C'\fR, in scalar context it should return
1074 the next line, or \f(CW\*(C`undef\*(C'\fR for no more data. In list context it should
1075 return all remaining lines, or an empty list for no more data. The strings
1076 returned should include the input record separator \f(CW$/\fR (see perlvar),
1077 unless it is \f(CW\*(C`undef\*(C'\fR (which means "slurp" mode).
1078 .Sp
1079 .Vb 10
1080 \& sub READLINE {
1081 \& my $r = shift;
1082 \& if (wantarray) {
1083 \& return ("all remaining\en",
1084 \& "lines up\en",
1085 \& "to eof\en");
1086 \& } else {
1087 \& return "READLINE called " . ++$$r . " times\en";
1088 \& }
1089 \& }
1090 .Ve
1091 .IP "GETC this" 4
1092 .IX Xref "GETC"
1093 .IX Item "GETC this"
1094 This method will be called when the \f(CW\*(C`getc\*(C'\fR function is called.
1095 .Sp
1096 .Vb 1
1097 \& sub GETC { print "Don\*(Aqt GETC, Get Perl"; return "a"; }
1098 .Ve
1099 .IP "EOF this" 4
1100 .IX Xref "EOF"
1101 .IX Item "EOF this"
1102 This method will be called when the \f(CW\*(C`eof\*(C'\fR function is called.
1103 .Sp
1104 Starting with Perl 5.12, an additional integer parameter will be passed. It
1105 will be zero if \f(CW\*(C`eof\*(C'\fR is called without parameter; \f(CW1\fR if \f(CW\*(C`eof\*(C'\fR is given
1106 a filehandle as a parameter, e.g. \f(CWeof(FH)\fR; and \f(CW2\fR in the very special
1107 case that the tied filehandle is \f(CW\*(C`ARGV\*(C'\fR and \f(CW\*(C`eof\*(C'\fR is called with an empty
1108 parameter list, e.g. \f(CWeof()\fR.
1109 .Sp
1110 .Vb 1
1111 \& sub EOF { not length $stringbuf }
1112 .Ve
1113 .IP "CLOSE this" 4
1114 .IX Xref "CLOSE"
1115 .IX Item "CLOSE this"
1116 This method will be called when the handle is closed via the \f(CW\*(C`close\*(C'\fR
1117 function.
1118 .Sp
1119 .Vb 1
1120 \& sub CLOSE { print "CLOSE called.\en" }
1121 .Ve
1122 .IP "UNTIE this" 4
1123 .IX Xref "UNTIE"
1124 .IX Item "UNTIE this"
1125 As with the other types of ties, this method will be called when \f(CW\*(C`untie\*(C'\fR happens.
1126 It may be appropriate to "auto CLOSE" when this occurs. See
1127 "The \f(CW\*(C`untie\*(C'\fR Gotcha" below.
1128 .IP "DESTROY this" 4
1129 .IX Xref "DESTROY"
1130 .IX Item "DESTROY this"
1131 As with the other types of ties, this method will be called when the
1132 tied handle is about to be destroyed. This is useful for debugging and
1133 possibly cleaning up.
1134 .Sp
1135 .Vb 1
1136 \& sub DESTROY { print "</shout>\en" }
1137 .Ve
1138 .PP
1139 Here\*(Aqs how to use our little example:
1140 .PP
1141 .Vb 5
1142 \& tie(*FOO,\*(AqShout\*(Aq);
1143 \& print FOO "hello\en";
1144 \& $x = 4; $y = 6;
1145 \& print FOO $x, " plus ", $y, " equals ", $x + $y, "\en";
1146 \& print <FOO>;
1147 .Ve
1148 .SS "UNTIE this"
1149 .IX Xref "UNTIE"
1150 .IX Subsection "UNTIE this"
1151 You can define for all tie types an UNTIE method that will be called
1152 at \fBuntie()\fR. See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below.
1153 .ie n .SS "The ""untie"" Gotcha"
1154 .el .SS "The \f(CWuntie\fP Gotcha"
1155 .IX Xref "untie"
1156 .IX Subsection "The untie Gotcha"
1157 If you intend making use of the object returned from either \fBtie()\fR or
1158 \&\fBtied()\fR, and if the tie\*(Aqs target class defines a destructor, there is a
1159 subtle gotcha you \fImust\fR guard against.
1160 .PP
1161 As setup, consider this (admittedly rather contrived) example of a
1162 tie; all it does is use a file to keep a log of the values assigned to
1163 a scalar.
1164 .PP
1165 .Vb 1
1166 \& package Remember;
1167 \&
1168 \& use v5.36;
1169 \& use IO::File;
1170 \&
1171 \& sub TIESCALAR {
1172 \& my $class = shift;
1173 \& my $filename = shift;
1174 \& my $handle = IO::File\->new( "> $filename" )
1175 \& or die "Cannot open $filename: $!\en";
1176 \&
1177 \& print $handle "The Start\en";
1178 \& bless {FH => $handle, Value => 0}, $class;
1179 \& }
1180 \&
1181 \& sub FETCH {
1182 \& my $self = shift;
1183 \& return $self\->{Value};
1184 \& }
1185 \&
1186 \& sub STORE {
1187 \& my $self = shift;
1188 \& my $value = shift;
1189 \& my $handle = $self\->{FH};
1190 \& print $handle "$value\en";
1191 \& $self\->{Value} = $value;
1192 \& }
1193 \&
1194 \& sub DESTROY {
1195 \& my $self = shift;
1196 \& my $handle = $self\->{FH};
1197 \& print $handle "The End\en";
1198 \& close $handle;
1199 \& }
1200 \&
1201 \& 1;
1202 .Ve
1203 .PP
1204 Here is an example that makes use of this tie:
1205 .PP
1206 .Vb 2
1207 \& use strict;
1208 \& use Remember;
1209 \&
1210 \& my $fred;
1211 \& tie $fred, \*(AqRemember\*(Aq, \*(Aqmyfile.txt\*(Aq;
1212 \& $fred = 1;
1213 \& $fred = 4;
1214 \& $fred = 5;
1215 \& untie $fred;
1216 \& system "cat myfile.txt";
1217 .Ve
1218 .PP
1219 This is the output when it is executed:
1220 .PP
1221 .Vb 5
1222 \& The Start
1223 \& 1
1224 \& 4
1225 \& 5
1226 \& The End
1227 .Ve
1228 .PP
1229 So far so good. Those of you who have been paying attention will have
1230 spotted that the tied object hasn\*(Aqt been used so far. So let\*(Aqs add an
1231 extra method to the Remember class to allow comments to be included in
1232 the file; say, something like this:
1233 .PP
1234 .Vb 6
1235 \& sub comment {
1236 \& my $self = shift;
1237 \& my $text = shift;
1238 \& my $handle = $self\->{FH};
1239 \& print $handle $text, "\en";
1240 \& }
1241 .Ve
1242 .PP
1243 And here is the previous example modified to use the \f(CW\*(C`comment\*(C'\fR method
1244 (which requires the tied object):
1245 .PP
1246 .Vb 2
1247 \& use strict;
1248 \& use Remember;
1249 \&
1250 \& my ($fred, $x);
1251 \& $x = tie $fred, \*(AqRemember\*(Aq, \*(Aqmyfile.txt\*(Aq;
1252 \& $fred = 1;
1253 \& $fred = 4;
1254 \& comment $x "changing...";
1255 \& $fred = 5;
1256 \& untie $fred;
1257 \& system "cat myfile.txt";
1258 .Ve
1259 .PP
1260 When this code is executed there is no output. Here\*(Aqs why:
1261 .PP
1262 When a variable is tied, it is associated with the object which is the
1263 return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
1264 object normally has only one reference, namely, the implicit reference
1265 from the tied variable. When \fBuntie()\fR is called, that reference is
1266 destroyed. Then, as in the first example above, the object\*(Aqs
1267 destructor (DESTROY) is called, which is normal for objects that have
1268 no more valid references; and thus the file is closed.
1269 .PP
1270 In the second example, however, we have stored another reference to
1271 the tied object in \f(CW$x\fR. That means that when \fBuntie()\fR gets called
1272 there will still be a valid reference to the object in existence, so
1273 the destructor is not called at that time, and thus the file is not
1274 closed. The reason there is no output is because the file buffers
1275 have not been flushed to disk.
1276 .PP
1277 Now that you know what the problem is, what can you do to avoid it?
1278 Prior to the introduction of the optional UNTIE method the only way
1279 was the good old \f(CW\*(C`\-w\*(C'\fR flag. Which will spot any instances where you call
1280 \&\fBuntie()\fR and there are still valid references to the tied object. If
1281 the second script above this near the top \f(CW\*(C`use warnings \*(Aquntie\*(Aq\*(C'\fR
1282 or was run with the \f(CW\*(C`\-w\*(C'\fR flag, Perl prints this
1283 warning message:
1284 .PP
1285 .Vb 1
1286 \& untie attempted while 1 inner references still exist
1287 .Ve
1288 .PP
1289 To get the script to work properly and silence the warning make sure
1290 there are no valid references to the tied object \fIbefore\fR \fBuntie()\fR is
1291 called:
1292 .PP
1293 .Vb 2
1294 \& undef $x;
1295 \& untie $fred;
1296 .Ve
1297 .PP
1298 Now that UNTIE exists the class designer can decide which parts of the
1299 class functionality are really associated with \f(CW\*(C`untie\*(C'\fR and which with
1300 the object being destroyed. What makes sense for a given class depends
1301 on whether the inner references are being kept so that non\-tie\-related
1302 methods can be called on the object. But in most cases it probably makes
1303 sense to move the functionality that would have been in DESTROY to the UNTIE
1304 method.
1305 .PP
1306 If the UNTIE method exists then the warning above does not occur. Instead the
1307 UNTIE method is passed the count of "extra" references and can issue its own
1308 warning if appropriate. e.g. to replicate the no UNTIE case this method can
1309 be used:
1310 .PP
1311 .Vb 6
1312 \& sub UNTIE
1313 \& {
1314 \& my ($obj,$count) = @_;
1315 \& carp "untie attempted while $count inner references still exist"
1316 \& if $count;
1317 \& }
1318 .Ve
1319 .SH "SEE ALSO"
1320 .IX Header "SEE ALSO"
1321 See DB_File or Config for some interesting \fBtie()\fR implementations.
1322 A good starting point for many \fBtie()\fR implementations is with one of the
1323 modules Tie::Scalar, Tie::Array, Tie::Hash, or Tie::Handle.
1324 .SH BUGS
1325 .IX Header "BUGS"
1326 The normal return provided by \f(CWscalar(%hash)\fR is not
1327 available. What this means is that using \f(CW%tied_hash\fR in boolean
1328 context doesn\*(Aqt work right (currently this always tests false,
1329 regardless of whether the hash is empty or hash elements).
1330 [ This paragraph needs review in light of changes in 5.25 ]
1331 .PP
1332 Localizing tied arrays or hashes does not work. After exiting the
1333 scope the arrays or the hashes are not restored.
1334 .PP
1335 Counting the number of entries in a hash via \f(CW\*(C`scalar(keys(%hash))\*(C'\fR
1336 or \f(CWscalar(values(%hash)\fR) is inefficient since it needs to iterate
1337 through all the entries with FIRSTKEY/NEXTKEY.
1338 .PP
1339 Tied hash/array slices cause multiple FETCH/STORE pairs, there are no
1340 tie methods for slice operations.
1341 .PP
1342 You cannot easily tie a multilevel data structure (such as a hash of
1343 hashes) to a dbm file. The first problem is that all but GDBM and
1344 Berkeley DB have size limitations, but beyond that, you also have problems
1345 with how references are to be represented on disk. One
1346 module that does attempt to address this need is DBM::Deep. Check your
1347 nearest CPAN site as described in perlmodlib for source code. Note
1348 that despite its name, DBM::Deep does not use dbm. Another earlier attempt
1349 at solving the problem is MLDBM, which is also available on the CPAN, but
1350 which has some fairly serious limitations.
1351 .PP
1352 Tied filehandles are still incomplete. \fBsysopen()\fR, \fBtruncate()\fR,
1353 \&\fBflock()\fR, \fBfcntl()\fR, \fBstat()\fR and \-X can\*(Aqt currently be trapped.
1354 .SH AUTHOR
1355 .IX Header "AUTHOR"
1356 Tom Christiansen
1357 .PP
1358 TIEHANDLE by Sven Verdoolaege <\[email protected]\fR> and Doug MacEachern <\[email protected]\fR>
1359 .PP
1360 UNTIE by Nick Ing\-Simmons <\fInick@ing\-simmons.net\fR>
1361 .PP
1362 SCALAR by Tassilo von Parseval <\fItassilo.von.parseval@rwth\-aachen.de\fR>
1363 .PP
1364 Tying Arrays by Casey West <\[email protected]\fR>