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