1PERLTIE(1) Perl Programmers Reference Guide PERLTIE(1)
2
3
4
6 perltie - how to hide an object class in a simple variable
7
9 tie VARIABLE, CLASSNAME, LIST
10
11 $object = tied VARIABLE
12
13 untie VARIABLE
14
16 Prior to release 5.0 of Perl, a programmer could use dbmopen() to con‐
17 nect an on-disk database in the standard Unix dbm(3x) format magically
18 to a %HASH in their program. However, their Perl was either built with
19 one particular dbm library or another, but not both, and you couldn't
20 extend this mechanism to other packages or types of variables.
21
22 Now you can.
23
24 The tie() function binds a variable to a class (package) that will pro‐
25 vide the implementation for access methods for that variable. Once
26 this magic has been performed, accessing a tied variable automatically
27 triggers method calls in the proper class. The complexity of the class
28 is hidden behind magic methods calls. The method names are in ALL
29 CAPS, which is a convention that Perl uses to indicate that they're
30 called implicitly rather than explicitly--just like the BEGIN() and
31 END() functions.
32
33 In the tie() call, "VARIABLE" is the name of the variable to be
34 enchanted. "CLASSNAME" is the name of a class implementing objects of
35 the correct type. Any additional arguments in the "LIST" are passed to
36 the appropriate constructor method for that class--meaning TIESCALAR(),
37 TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments
38 such as might be passed to the dbminit() function of C.) The object
39 returned by the "new" method is also returned by the tie() function,
40 which would be useful if you wanted to access other methods in "CLASS‐
41 NAME". (You don't actually have to return a reference to a right "type"
42 (e.g., HASH or "CLASSNAME") so long as it's a properly blessed object.)
43 You can also retrieve a reference to the underlying object using the
44 tied() function.
45
46 Unlike dbmopen(), the tie() function will not "use" or "require" a mod‐
47 ule for you--you need to do that explicitly yourself.
48
49 Tying Scalars
50
51 A class implementing a tied scalar should define the following methods:
52 TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
53
54 Let's look at each in turn, using as an example a tie class for scalars
55 that allows the user to do something like:
56
57 tie $his_speed, 'Nice', getppid();
58 tie $my_speed, 'Nice', $$;
59
60 And now whenever either of those variables is accessed, its current
61 system priority is retrieved and returned. If those variables are set,
62 then the process's priority is changed!
63
64 We'll use Jarkko Hietaniemi <jhi@iki.fi>'s BSD::Resource class (not
65 included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
66 from your system, as well as the getpriority() and setpriority() system
67 calls. Here's the preamble of the class.
68
69 package Nice;
70 use Carp;
71 use BSD::Resource;
72 use strict;
73 $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
74
75 TIESCALAR classname, LIST
76 This is the constructor for the class. That means it is expected
77 to return a blessed reference to a new scalar (probably anonymous)
78 that it's creating. For example:
79
80 sub TIESCALAR {
81 my $class = shift;
82 my $pid = shift ⎪⎪ $$; # 0 means me
83
84 if ($pid !~ /^\d+$/) {
85 carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
86 return undef;
87 }
88
89 unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
90 carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
91 return undef;
92 }
93
94 return bless \$pid, $class;
95 }
96
97 This tie class has chosen to return an error rather than raising an
98 exception if its constructor should fail. While this is how
99 dbmopen() works, other classes may well not wish to be so forgiv‐
100 ing. It checks the global variable $^W to see whether to emit a
101 bit of noise anyway.
102
103 FETCH this
104 This method will be triggered every time the tied variable is
105 accessed (read). It takes no arguments beyond its self reference,
106 which is the object representing the scalar we're dealing with.
107 Because in this case we're using just a SCALAR ref for the tied
108 scalar object, a simple $$self allows the method to get at the real
109 value stored there. In our example below, that real value is the
110 process ID to which we've tied our variable.
111
112 sub FETCH {
113 my $self = shift;
114 confess "wrong type" unless ref $self;
115 croak "usage error" if @_;
116 my $nicety;
117 local($!) = 0;
118 $nicety = getpriority(PRIO_PROCESS, $$self);
119 if ($!) { croak "getpriority failed: $!" }
120 return $nicety;
121 }
122
123 This time we've decided to blow up (raise an exception) if the
124 renice fails--there's no place for us to return an error otherwise,
125 and it's probably the right thing to do.
126
127 STORE this, value
128 This method will be triggered every time the tied variable is set
129 (assigned). Beyond its self reference, it also expects one (and
130 only one) argument--the new value the user is trying to assign.
131 Don't worry about returning a value from STORE -- the semantic of
132 assignment returning the assigned value is implemented with FETCH.
133
134 sub STORE {
135 my $self = shift;
136 confess "wrong type" unless ref $self;
137 my $new_nicety = shift;
138 croak "usage error" if @_;
139
140 if ($new_nicety < PRIO_MIN) {
141 carp sprintf
142 "WARNING: priority %d less than minimum system priority %d",
143 $new_nicety, PRIO_MIN if $^W;
144 $new_nicety = PRIO_MIN;
145 }
146
147 if ($new_nicety > PRIO_MAX) {
148 carp sprintf
149 "WARNING: priority %d greater than maximum system priority %d",
150 $new_nicety, PRIO_MAX if $^W;
151 $new_nicety = PRIO_MAX;
152 }
153
154 unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) {
155 confess "setpriority failed: $!";
156 }
157 }
158
159 UNTIE this
160 This method will be triggered when the "untie" occurs. This can be
161 useful if the class needs to know when no further calls will be
162 made. (Except DESTROY of course.) See "The "untie" Gotcha" below
163 for more details.
164
165 DESTROY this
166 This method will be triggered when the tied variable needs to be
167 destructed. As with other object classes, such a method is seldom
168 necessary, because Perl deallocates its moribund object's memory
169 for you automatically--this isn't C++, you know. We'll use a
170 DESTROY method here for debugging purposes only.
171
172 sub DESTROY {
173 my $self = shift;
174 confess "wrong type" unless ref $self;
175 carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
176 }
177
178 That's about all there is to it. Actually, it's more than all there is
179 to it, because we've done a few nice things here for the sake of com‐
180 pleteness, robustness, and general aesthetics. Simpler TIESCALAR
181 classes are certainly possible.
182
183 Tying Arrays
184
185 A class implementing a tied ordinary array should define the following
186 methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE
187 and/or DESTROY.
188
189 FETCHSIZE and STORESIZE are used to provide $#array and equivalent
190 "scalar(@array)" access.
191
192 The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are
193 required if the perl operator with the corresponding (but lowercase)
194 name is to operate on the tied array. The Tie::Array class can be used
195 as a base class to implement the first five of these in terms of the
196 basic methods above. The default implementations of DELETE and EXISTS
197 in Tie::Array simply "croak".
198
199 In addition EXTEND will be called when perl would have pre-extended
200 allocation in a real array.
201
202 For this discussion, we'll implement an array whose elements are a
203 fixed size at creation. If you try to create an element larger than
204 the fixed size, you'll take an exception. For example:
205
206 use FixedElem_Array;
207 tie @array, 'FixedElem_Array', 3;
208 $array[0] = 'cat'; # ok.
209 $array[1] = 'dogs'; # exception, length('dogs') > 3.
210
211 The preamble code for the class is as follows:
212
213 package FixedElem_Array;
214 use Carp;
215 use strict;
216
217 TIEARRAY classname, LIST
218 This is the constructor for the class. That means it is expected
219 to return a blessed reference through which the new array (probably
220 an anonymous ARRAY ref) will be accessed.
221
222 In our example, just to show you that you don't really have to
223 return an ARRAY reference, we'll choose a HASH reference to repre‐
224 sent our object. A HASH works out well as a generic record type:
225 the "{ELEMSIZE}" field will store the maximum element size allowed,
226 and the "{ARRAY}" field will hold the true ARRAY ref. If someone
227 outside the class tries to dereference the object returned (doubt‐
228 less thinking it an ARRAY ref), they'll blow up. This just goes to
229 show you that you should respect an object's privacy.
230
231 sub TIEARRAY {
232 my $class = shift;
233 my $elemsize = shift;
234 if ( @_ ⎪⎪ $elemsize =~ /\D/ ) {
235 croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
236 }
237 return bless {
238 ELEMSIZE => $elemsize,
239 ARRAY => [],
240 }, $class;
241 }
242
243 FETCH this, index
244 This method will be triggered every time an individual element the
245 tied array is accessed (read). It takes one argument beyond its
246 self reference: the index whose value we're trying to fetch.
247
248 sub FETCH {
249 my $self = shift;
250 my $index = shift;
251 return $self->{ARRAY}->[$index];
252 }
253
254 If a negative array index is used to read from an array, the index
255 will be translated to a positive one internally by calling FETCH‐
256 SIZE before being passed to FETCH. You may disable this feature by
257 assigning a true value to the variable $NEGATIVE_INDICES in the
258 tied array class.
259
260 As you may have noticed, the name of the FETCH method (et al.) is
261 the same for all accesses, even though the constructors differ in
262 names (TIESCALAR vs TIEARRAY). While in theory you could have the
263 same class servicing several tied types, in practice this becomes
264 cumbersome, and it's easiest to keep them at simply one tie type
265 per class.
266
267 STORE this, index, value
268 This method will be triggered every time an element in the tied
269 array is set (written). It takes two arguments beyond its self
270 reference: the index at which we're trying to store something and
271 the value we're trying to put there.
272
273 In our example, "undef" is really "$self->{ELEMSIZE}" number of
274 spaces so we have a little more work to do here:
275
276 sub STORE {
277 my $self = shift;
278 my( $index, $value ) = @_;
279 if ( length $value > $self->{ELEMSIZE} ) {
280 croak "length of $value is greater than $self->{ELEMSIZE}";
281 }
282 # fill in the blanks
283 $self->EXTEND( $index ) if $index > $self->FETCHSIZE();
284 # right justify to keep element size for smaller elements
285 $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
286 }
287
288 Negative indexes are treated the same as with FETCH.
289
290 FETCHSIZE this
291 Returns the total number of items in the tied array associated with
292 object this. (Equivalent to "scalar(@array)"). For example:
293
294 sub FETCHSIZE {
295 my $self = shift;
296 return scalar @{$self->{ARRAY}};
297 }
298
299 STORESIZE this, count
300 Sets the total number of items in the tied array associated with
301 object this to be count. If this makes the array larger then
302 class's mapping of "undef" should be returned for new positions.
303 If the array becomes smaller then entries beyond count should be
304 deleted.
305
306 In our example, 'undef' is really an element containing
307 "$self->{ELEMSIZE}" number of spaces. Observe:
308
309 sub STORESIZE {
310 my $self = shift;
311 my $count = shift;
312 if ( $count > $self->FETCHSIZE() ) {
313 foreach ( $count - $self->FETCHSIZE() .. $count ) {
314 $self->STORE( $_, '' );
315 }
316 } elsif ( $count < $self->FETCHSIZE() ) {
317 foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
318 $self->POP();
319 }
320 }
321 }
322
323 EXTEND this, count
324 Informative call that array is likely to grow to have count
325 entries. Can be used to optimize allocation. This method need do
326 nothing.
327
328 In our example, we want to make sure there are no blank ("undef")
329 entries, so "EXTEND" will make use of "STORESIZE" to fill elements
330 as needed:
331
332 sub EXTEND {
333 my $self = shift;
334 my $count = shift;
335 $self->STORESIZE( $count );
336 }
337
338 EXISTS this, key
339 Verify that the element at index key exists in the tied array this.
340
341 In our example, we will determine that if an element consists of
342 "$self->{ELEMSIZE}" spaces only, it does not exist:
343
344 sub EXISTS {
345 my $self = shift;
346 my $index = shift;
347 return 0 if ! defined $self->{ARRAY}->[$index] ⎪⎪
348 $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
349 return 1;
350 }
351
352 DELETE this, key
353 Delete the element at index key from the tied array this.
354
355 In our example, a deleted item is "$self->{ELEMSIZE}" spaces:
356
357 sub DELETE {
358 my $self = shift;
359 my $index = shift;
360 return $self->STORE( $index, '' );
361 }
362
363 CLEAR this
364 Clear (remove, delete, ...) all values from the tied array associ‐
365 ated with object this. For example:
366
367 sub CLEAR {
368 my $self = shift;
369 return $self->{ARRAY} = [];
370 }
371
372 PUSH this, LIST
373 Append elements of LIST to the array. For example:
374
375 sub PUSH {
376 my $self = shift;
377 my @list = @_;
378 my $last = $self->FETCHSIZE();
379 $self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
380 return $self->FETCHSIZE();
381 }
382
383 POP this
384 Remove last element of the array and return it. For example:
385
386 sub POP {
387 my $self = shift;
388 return pop @{$self->{ARRAY}};
389 }
390
391 SHIFT this
392 Remove the first element of the array (shifting other elements
393 down) and return it. For example:
394
395 sub SHIFT {
396 my $self = shift;
397 return shift @{$self->{ARRAY}};
398 }
399
400 UNSHIFT this, LIST
401 Insert LIST elements at the beginning of the array, moving existing
402 elements up to make room. For example:
403
404 sub UNSHIFT {
405 my $self = shift;
406 my @list = @_;
407 my $size = scalar( @list );
408 # make room for our list
409 @{$self->{ARRAY}}[ $size .. $#{$self->{ARRAY}} + $size ]
410 = @{$self->{ARRAY}};
411 $self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
412 }
413
414 SPLICE this, offset, length, LIST
415 Perform the equivalent of "splice" on the array.
416
417 offset is optional and defaults to zero, negative values count back
418 from the end of the array.
419
420 length is optional and defaults to rest of the array.
421
422 LIST may be empty.
423
424 Returns a list of the original length elements at offset.
425
426 In our example, we'll use a little shortcut if there is a LIST:
427
428 sub SPLICE {
429 my $self = shift;
430 my $offset = shift ⎪⎪ 0;
431 my $length = shift ⎪⎪ $self->FETCHSIZE() - $offset;
432 my @list = ();
433 if ( @_ ) {
434 tie @list, __PACKAGE__, $self->{ELEMSIZE};
435 @list = @_;
436 }
437 return splice @{$self->{ARRAY}}, $offset, $length, @list;
438 }
439
440 UNTIE this
441 Will be called when "untie" happens. (See "The "untie" Gotcha"
442 below.)
443
444 DESTROY this
445 This method will be triggered when the tied variable needs to be
446 destructed. As with the scalar tie class, this is almost never
447 needed in a language that does its own garbage collection, so this
448 time we'll just leave it out.
449
450 Tying Hashes
451
452 Hashes were the first Perl data type to be tied (see dbmopen()). A
453 class implementing a tied hash should define the following methods:
454 TIEHASH is the constructor. FETCH and STORE access the key and value
455 pairs. EXISTS reports whether a key is present in the hash, and DELETE
456 deletes one. CLEAR empties the hash by deleting all the key and value
457 pairs. FIRSTKEY and NEXTKEY implement the keys() and each() functions
458 to iterate over all the keys. SCALAR is triggered when the tied hash is
459 evaluated in scalar context. UNTIE is called when "untie" happens, and
460 DESTROY is called when the tied variable is garbage collected.
461
462 If this seems like a lot, then feel free to inherit from merely the
463 standard Tie::StdHash module for most of your methods, redefining only
464 the interesting ones. See Tie::Hash for details.
465
466 Remember that Perl distinguishes between a key not existing in the
467 hash, and the key existing in the hash but having a corresponding value
468 of "undef". The two possibilities can be tested with the "exists()"
469 and "defined()" functions.
470
471 Here's an example of a somewhat interesting tied hash class: it gives
472 you a hash representing a particular user's dot files. You index into
473 the hash with the name of the file (minus the dot) and you get back
474 that dot file's contents. For example:
475
476 use DotFiles;
477 tie %dot, 'DotFiles';
478 if ( $dot{profile} =~ /MANPATH/ ⎪⎪
479 $dot{login} =~ /MANPATH/ ⎪⎪
480 $dot{cshrc} =~ /MANPATH/ )
481 {
482 print "you seem to set your MANPATH\n";
483 }
484
485 Or here's another sample of using our tied class:
486
487 tie %him, 'DotFiles', 'daemon';
488 foreach $f ( keys %him ) {
489 printf "daemon dot file %s is size %d\n",
490 $f, length $him{$f};
491 }
492
493 In our tied hash DotFiles example, we use a regular hash for the object
494 containing several important fields, of which only the "{LIST}" field
495 will be what the user thinks of as the real hash.
496
497 USER whose dot files this object represents
498
499 HOME where those dot files live
500
501 CLOBBER
502 whether we should try to change or remove those dot files
503
504 LIST the hash of dot file names and content mappings
505
506 Here's the start of Dotfiles.pm:
507
508 package DotFiles;
509 use Carp;
510 sub whowasi { (caller(1))[3] . '()' }
511 my $DEBUG = 0;
512 sub debug { $DEBUG = @_ ? shift : 1 }
513
514 For our example, we want to be able to emit debugging info to help in
515 tracing during development. We keep also one convenience function
516 around internally to help print out warnings; whowasi() returns the
517 function name that calls it.
518
519 Here are the methods for the DotFiles tied hash.
520
521 TIEHASH classname, LIST
522 This is the constructor for the class. That means it is expected
523 to return a blessed reference through which the new object (proba‐
524 bly but not necessarily an anonymous hash) will be accessed.
525
526 Here's the constructor:
527
528 sub TIEHASH {
529 my $self = shift;
530 my $user = shift ⎪⎪ $>;
531 my $dotdir = shift ⎪⎪ '';
532 croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
533 $user = getpwuid($user) if $user =~ /^\d+$/;
534 my $dir = (getpwnam($user))[7]
535 ⎪⎪ croak "@{[&whowasi]}: no user $user";
536 $dir .= "/$dotdir" if $dotdir;
537
538 my $node = {
539 USER => $user,
540 HOME => $dir,
541 LIST => {},
542 CLOBBER => 0,
543 };
544
545 opendir(DIR, $dir)
546 ⎪⎪ croak "@{[&whowasi]}: can't opendir $dir: $!";
547 foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
548 $dot =~ s/^\.//;
549 $node->{LIST}{$dot} = undef;
550 }
551 closedir DIR;
552 return bless $node, $self;
553 }
554
555 It's probably worth mentioning that if you're going to filetest the
556 return values out of a readdir, you'd better prepend the directory
557 in question. Otherwise, because we didn't chdir() there, it would
558 have been testing the wrong file.
559
560 FETCH this, key
561 This method will be triggered every time an element in the tied
562 hash is accessed (read). It takes one argument beyond its self
563 reference: the key whose value we're trying to fetch.
564
565 Here's the fetch for our DotFiles example.
566
567 sub FETCH {
568 carp &whowasi if $DEBUG;
569 my $self = shift;
570 my $dot = shift;
571 my $dir = $self->{HOME};
572 my $file = "$dir/.$dot";
573
574 unless (exists $self->{LIST}->{$dot} ⎪⎪ -f $file) {
575 carp "@{[&whowasi]}: no $dot file" if $DEBUG;
576 return undef;
577 }
578
579 if (defined $self->{LIST}->{$dot}) {
580 return $self->{LIST}->{$dot};
581 } else {
582 return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
583 }
584 }
585
586 It was easy to write by having it call the Unix cat(1) command, but
587 it would probably be more portable to open the file manually (and
588 somewhat more efficient). Of course, because dot files are a Unixy
589 concept, we're not that concerned.
590
591 STORE this, key, value
592 This method will be triggered every time an element in the tied
593 hash is set (written). It takes two arguments beyond its self ref‐
594 erence: the index at which we're trying to store something, and the
595 value we're trying to put there.
596
597 Here in our DotFiles example, we'll be careful not to let them try
598 to overwrite the file unless they've called the clobber() method on
599 the original object reference returned by tie().
600
601 sub STORE {
602 carp &whowasi if $DEBUG;
603 my $self = shift;
604 my $dot = shift;
605 my $value = shift;
606 my $file = $self->{HOME} . "/.$dot";
607 my $user = $self->{USER};
608
609 croak "@{[&whowasi]}: $file not clobberable"
610 unless $self->{CLOBBER};
611
612 open(F, "> $file") ⎪⎪ croak "can't open $file: $!";
613 print F $value;
614 close(F);
615 }
616
617 If they wanted to clobber something, they might say:
618
619 $ob = tie %daemon_dots, 'daemon';
620 $ob->clobber(1);
621 $daemon_dots{signature} = "A true daemon\n";
622
623 Another way to lay hands on a reference to the underlying object is
624 to use the tied() function, so they might alternately have set
625 clobber using:
626
627 tie %daemon_dots, 'daemon';
628 tied(%daemon_dots)->clobber(1);
629
630 The clobber method is simply:
631
632 sub clobber {
633 my $self = shift;
634 $self->{CLOBBER} = @_ ? shift : 1;
635 }
636
637 DELETE this, key
638 This method is triggered when we remove an element from the hash,
639 typically by using the delete() function. Again, we'll be careful
640 to check whether they really want to clobber files.
641
642 sub DELETE {
643 carp &whowasi if $DEBUG;
644
645 my $self = shift;
646 my $dot = shift;
647 my $file = $self->{HOME} . "/.$dot";
648 croak "@{[&whowasi]}: won't remove file $file"
649 unless $self->{CLOBBER};
650 delete $self->{LIST}->{$dot};
651 my $success = unlink($file);
652 carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
653 $success;
654 }
655
656 The value returned by DELETE becomes the return value of the call
657 to delete(). If you want to emulate the normal behavior of
658 delete(), you should return whatever FETCH would have returned for
659 this key. In this example, we have chosen instead to return a
660 value which tells the caller whether the file was successfully
661 deleted.
662
663 CLEAR this
664 This method is triggered when the whole hash is to be cleared, usu‐
665 ally by assigning the empty list to it.
666
667 In our example, that would remove all the user's dot files! It's
668 such a dangerous thing that they'll have to set CLOBBER to some‐
669 thing higher than 1 to make it happen.
670
671 sub CLEAR {
672 carp &whowasi if $DEBUG;
673 my $self = shift;
674 croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
675 unless $self->{CLOBBER} > 1;
676 my $dot;
677 foreach $dot ( keys %{$self->{LIST}}) {
678 $self->DELETE($dot);
679 }
680 }
681
682 EXISTS this, key
683 This method is triggered when the user uses the exists() function
684 on a particular hash. In our example, we'll look at the "{LIST}"
685 hash element for this:
686
687 sub EXISTS {
688 carp &whowasi if $DEBUG;
689 my $self = shift;
690 my $dot = shift;
691 return exists $self->{LIST}->{$dot};
692 }
693
694 FIRSTKEY this
695 This method will be triggered when the user is going to iterate
696 through the hash, such as via a keys() or each() call.
697
698 sub FIRSTKEY {
699 carp &whowasi if $DEBUG;
700 my $self = shift;
701 my $a = keys %{$self->{LIST}}; # reset each() iterator
702 each %{$self->{LIST}}
703 }
704
705 NEXTKEY this, lastkey
706 This method gets triggered during a keys() or each() iteration. It
707 has a second argument which is the last key that had been accessed.
708 This is useful if you're carrying about ordering or calling the
709 iterator from more than one sequence, or not really storing things
710 in a hash anywhere.
711
712 For our example, we're using a real hash so we'll do just the sim‐
713 ple thing, but we'll have to go through the LIST field indirectly.
714
715 sub NEXTKEY {
716 carp &whowasi if $DEBUG;
717 my $self = shift;
718 return each %{ $self->{LIST} }
719 }
720
721 SCALAR this
722 This is called when the hash is evaluated in scalar context. In
723 order to mimic the behaviour of untied hashes, this method should
724 return a false value when the tied hash is considered empty. If
725 this method does not exist, perl will make some educated guesses
726 and return true when the hash is inside an iteration. If this isn't
727 the case, FIRSTKEY is called, and the result will be a false value
728 if FIRSTKEY returns the empty list, true otherwise.
729
730 However, you should not blindly rely on perl always doing the right
731 thing. Particularly, perl will mistakenly return true when you
732 clear the hash by repeatedly calling DELETE until it is empty. You
733 are therefore advised to supply your own SCALAR method when you
734 want to be absolutely sure that your hash behaves nicely in scalar
735 context.
736
737 In our example we can just call "scalar" on the underlying hash
738 referenced by "$self->{LIST}":
739
740 sub SCALAR {
741 carp &whowasi if $DEBUG;
742 my $self = shift;
743 return scalar %{ $self->{LIST} }
744 }
745
746 UNTIE this
747 This is called when "untie" occurs. See "The "untie" Gotcha"
748 below.
749
750 DESTROY this
751 This method is triggered when a tied hash is about to go out of
752 scope. You don't really need it unless you're trying to add debug‐
753 ging or have auxiliary state to clean up. Here's a very simple
754 function:
755
756 sub DESTROY {
757 carp &whowasi if $DEBUG;
758 }
759
760 Note that functions such as keys() and values() may return huge lists
761 when used on large objects, like DBM files. You may prefer to use the
762 each() function to iterate over such. Example:
763
764 # print out history file offsets
765 use NDBM_File;
766 tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
767 while (($key,$val) = each %HIST) {
768 print $key, ' = ', unpack('L',$val), "\n";
769 }
770 untie(%HIST);
771
772 Tying FileHandles
773
774 This is partially implemented now.
775
776 A class implementing a tied filehandle should define the following
777 methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE,
778 GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The class can also
779 provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding
780 perl operators are used on the handle.
781
782 When STDERR is tied, its PRINT method will be called to issue warnings
783 and error messages. This feature is temporarily disabled during the
784 call, which means you can use "warn()" inside PRINT without starting a
785 recursive loop. And just like "__WARN__" and "__DIE__" handlers,
786 STDERR's PRINT method may be called to report parser errors, so the
787 caveats mentioned under "%SIG" in perlvar apply.
788
789 All of this is especially useful when perl is embedded in some other
790 program, where output to STDOUT and STDERR may have to be redirected in
791 some special way. See nvi and the Apache module for examples.
792
793 In our example we're going to create a shouting handle.
794
795 package Shout;
796
797 TIEHANDLE classname, LIST
798 This is the constructor for the class. That means it is expected
799 to return a blessed reference of some sort. The reference can be
800 used to hold some internal information.
801
802 sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
803
804 WRITE this, LIST
805 This method will be called when the handle is written to via the
806 "syswrite" function.
807
808 sub WRITE {
809 $r = shift;
810 my($buf,$len,$offset) = @_;
811 print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
812 }
813
814 PRINT this, LIST
815 This method will be triggered every time the tied handle is printed
816 to with the "print()" function. Beyond its self reference it also
817 expects the list that was passed to the print function.
818
819 sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
820
821 PRINTF this, LIST
822 This method will be triggered every time the tied handle is printed
823 to with the "printf()" function. Beyond its self reference it also
824 expects the format and list that was passed to the printf function.
825
826 sub PRINTF {
827 shift;
828 my $fmt = shift;
829 print sprintf($fmt, @_);
830 }
831
832 READ this, LIST
833 This method will be called when the handle is read from via the
834 "read" or "sysread" functions.
835
836 sub READ {
837 my $self = shift;
838 my $bufref = \$_[0];
839 my(undef,$len,$offset) = @_;
840 print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
841 # add to $$bufref, set $len to number of characters read
842 $len;
843 }
844
845 READLINE this
846 This method will be called when the handle is read from via <HAN‐
847 DLE>. The method should return undef when there is no more data.
848
849 sub READLINE { $r = shift; "READLINE called $$r times\n"; }
850
851 GETC this
852 This method will be called when the "getc" function is called.
853
854 sub GETC { print "Don't GETC, Get Perl"; return "a"; }
855
856 CLOSE this
857 This method will be called when the handle is closed via the
858 "close" function.
859
860 sub CLOSE { print "CLOSE called.\n" }
861
862 UNTIE this
863 As with the other types of ties, this method will be called when
864 "untie" happens. It may be appropriate to "auto CLOSE" when this
865 occurs. See "The "untie" Gotcha" below.
866
867 DESTROY this
868 As with the other types of ties, this method will be called when
869 the tied handle is about to be destroyed. This is useful for debug‐
870 ging and possibly cleaning up.
871
872 sub DESTROY { print "</shout>\n" }
873
874 Here's how to use our little example:
875
876 tie(*FOO,'Shout');
877 print FOO "hello\n";
878 $a = 4; $b = 6;
879 print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
880 print <FOO>;
881
882 UNTIE this
883
884 You can define for all tie types an UNTIE method that will be called at
885 untie(). See "The "untie" Gotcha" below.
886
887 The "untie" Gotcha
888
889 If you intend making use of the object returned from either tie() or
890 tied(), and if the tie's target class defines a destructor, there is a
891 subtle gotcha you must guard against.
892
893 As setup, consider this (admittedly rather contrived) example of a tie;
894 all it does is use a file to keep a log of the values assigned to a
895 scalar.
896
897 package Remember;
898
899 use strict;
900 use warnings;
901 use IO::File;
902
903 sub TIESCALAR {
904 my $class = shift;
905 my $filename = shift;
906 my $handle = new IO::File "> $filename"
907 or die "Cannot open $filename: $!\n";
908
909 print $handle "The Start\n";
910 bless {FH => $handle, Value => 0}, $class;
911 }
912
913 sub FETCH {
914 my $self = shift;
915 return $self->{Value};
916 }
917
918 sub STORE {
919 my $self = shift;
920 my $value = shift;
921 my $handle = $self->{FH};
922 print $handle "$value\n";
923 $self->{Value} = $value;
924 }
925
926 sub DESTROY {
927 my $self = shift;
928 my $handle = $self->{FH};
929 print $handle "The End\n";
930 close $handle;
931 }
932
933 1;
934
935 Here is an example that makes use of this tie:
936
937 use strict;
938 use Remember;
939
940 my $fred;
941 tie $fred, 'Remember', 'myfile.txt';
942 $fred = 1;
943 $fred = 4;
944 $fred = 5;
945 untie $fred;
946 system "cat myfile.txt";
947
948 This is the output when it is executed:
949
950 The Start
951 1
952 4
953 5
954 The End
955
956 So far so good. Those of you who have been paying attention will have
957 spotted that the tied object hasn't been used so far. So lets add an
958 extra method to the Remember class to allow comments to be included in
959 the file -- say, something like this:
960
961 sub comment {
962 my $self = shift;
963 my $text = shift;
964 my $handle = $self->{FH};
965 print $handle $text, "\n";
966 }
967
968 And here is the previous example modified to use the "comment" method
969 (which requires the tied object):
970
971 use strict;
972 use Remember;
973
974 my ($fred, $x);
975 $x = tie $fred, 'Remember', 'myfile.txt';
976 $fred = 1;
977 $fred = 4;
978 comment $x "changing...";
979 $fred = 5;
980 untie $fred;
981 system "cat myfile.txt";
982
983 When this code is executed there is no output. Here's why:
984
985 When a variable is tied, it is associated with the object which is the
986 return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
987 object normally has only one reference, namely, the implicit reference
988 from the tied variable. When untie() is called, that reference is
989 destroyed. Then, as in the first example above, the object's destruc‐
990 tor (DESTROY) is called, which is normal for objects that have no more
991 valid references; and thus the file is closed.
992
993 In the second example, however, we have stored another reference to the
994 tied object in $x. That means that when untie() gets called there will
995 still be a valid reference to the object in existence, so the destruc‐
996 tor is not called at that time, and thus the file is not closed. The
997 reason there is no output is because the file buffers have not been
998 flushed to disk.
999
1000 Now that you know what the problem is, what can you do to avoid it?
1001 Prior to the introduction of the optional UNTIE method the only way was
1002 the good old "-w" flag. Which will spot any instances where you call
1003 untie() and there are still valid references to the tied object. If
1004 the second script above this near the top "use warnings 'untie'" or was
1005 run with the "-w" flag, Perl prints this warning message:
1006
1007 untie attempted while 1 inner references still exist
1008
1009 To get the script to work properly and silence the warning make sure
1010 there are no valid references to the tied object before untie() is
1011 called:
1012
1013 undef $x;
1014 untie $fred;
1015
1016 Now that UNTIE exists the class designer can decide which parts of the
1017 class functionality are really associated with "untie" and which with
1018 the object being destroyed. What makes sense for a given class depends
1019 on whether the inner references are being kept so that non-tie-related
1020 methods can be called on the object. But in most cases it probably
1021 makes sense to move the functionality that would have been in DESTROY
1022 to the UNTIE method.
1023
1024 If the UNTIE method exists then the warning above does not occur.
1025 Instead the UNTIE method is passed the count of "extra" references and
1026 can issue its own warning if appropriate. e.g. to replicate the no
1027 UNTIE case this method can be used:
1028
1029 sub UNTIE
1030 {
1031 my ($obj,$count) = @_;
1032 carp "untie attempted while $count inner references still exist" if $count;
1033 }
1034
1036 See DB_File or Config for some interesting tie() implementations. A
1037 good starting point for many tie() implementations is with one of the
1038 modules Tie::Scalar, Tie::Array, Tie::Hash, or Tie::Handle.
1039
1041 The bucket usage information provided by "scalar(%hash)" is not avail‐
1042 able. What this means is that using %tied_hash in boolean context
1043 doesn't work right (currently this always tests false, regardless of
1044 whether the hash is empty or hash elements).
1045
1046 Localizing tied arrays or hashes does not work. After exiting the
1047 scope the arrays or the hashes are not restored.
1048
1049 Counting the number of entries in a hash via "scalar(keys(%hash))" or
1050 "scalar(values(%hash)") is inefficient since it needs to iterate
1051 through all the entries with FIRSTKEY/NEXTKEY.
1052
1053 Tied hash/array slices cause multiple FETCH/STORE pairs, there are no
1054 tie methods for slice operations.
1055
1056 You cannot easily tie a multilevel data structure (such as a hash of
1057 hashes) to a dbm file. The first problem is that all but GDBM and
1058 Berkeley DB have size limitations, but beyond that, you also have prob‐
1059 lems with how references are to be represented on disk. One experimen‐
1060 tal module that does attempt to address this need is DBM::Deep. Check
1061 your nearest CPAN site as described in perlmodlib for source code.
1062 Note that despite its name, DBM::Deep does not use dbm. Another ear‐
1063 lier attempt at solving the problem is MLDBM, which is also available
1064 on the CPAN, but which has some fairly serious limitations.
1065
1066 Tied filehandles are still incomplete. sysopen(), truncate(), flock(),
1067 fcntl(), stat() and -X can't currently be trapped.
1068
1070 Tom Christiansen
1071
1072 TIEHANDLE by Sven Verdoolaege <skimo@dns.ufsia.ac.be> and Doug MacEach‐
1073 ern <dougm@osf.org>
1074
1075 UNTIE by Nick Ing-Simmons <nick@ing-simmons.net>
1076
1077 SCALAR by Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>
1078
1079 Tying Arrays by Casey West <casey@geeknest.com>
1080
1081
1082
1083perl v5.8.8 2006-01-07 PERLTIE(1)