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