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