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