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