Debian Codegraph @

upstream/debian-unstable/man1/perltie.1

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