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">
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:" />
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"> perltie - how to hide an object class in a simple variable
</span></strong></big>
17 <p><a name=
"__index__"></a></p>
22 <li><a href=
"#name">NAME
</a></li>
23 <li><a href=
"#synopsis">SYNOPSIS
</a></li>
24 <li><a href=
"#description">DESCRIPTION
</a></li>
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>
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>
44 <h1><a name=
"name_x_tie_">NAME
46 <p>perltie - how to hide an object class in a simple variable
</p>
50 <h1><a name=
"synopsis">SYNOPSIS
</a></h1>
52 tie VARIABLE, CLASSNAME, LIST
</pre>
54 $object = tied VARIABLE
</pre>
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>
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>
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>
91 <h2><a name=
"tying_scalars_x_scalar__tying_">Tying Scalars
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>
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
<<em><a href=
"mailto:jhi@iki.fi">jhi@iki.fi
</a></em>>'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>
112 $Nice::DEBUG =
0 unless defined $Nice::DEBUG;
</pre>
114 <dt><strong><a name=
"item_tiescalar_classname_2c_list_x_3ctiescalar_3e">TIESCALAR classname, LIST
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>
126 my $pid = shift || $$; #
0 means me
</pre>
130 if ($pid !~ /^\d+$/) {
131 carp
"Nice::Tie::Scalar got non-numeric pid $pid
" if $^W;
137 unless (kill
0, $pid) { # EPERM or ERSCH, no doubt
138 carp
"Nice::Tie::Scalar got bad pid $pid: $!
" if $^W;
144 return bless \$pid, $class;
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>
154 <dt><strong><a name=
"item_fetch_this_x_3cfetch_3e">FETCH this
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>
169 confess
"wrong type
" unless ref $self;
170 croak
"usage error
" if @_;
173 $nicety = getpriority(PRIO_PROCESS, $$self);
174 if ($!) { croak
"getpriority failed: $!
" }
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>
184 <dt><strong><a name=
"item_store_this_2c_value_x_3cstore_3e">STORE this, value
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>
198 confess
"wrong type
" unless ref $self;
199 my $new_nicety = shift;
200 croak
"usage error
" if @_;
</pre>
204 if ($new_nicety
< PRIO_MIN) {
206 "WARNING: priority %d less than minimum system priority %d
",
207 $new_nicety, PRIO_MIN if $^W;
208 $new_nicety = PRIO_MIN;
213 if ($new_nicety
> PRIO_MAX) {
215 "WARNING: priority %d greater than maximum system priority %d
",
216 $new_nicety, PRIO_MAX if $^W;
217 $new_nicety = PRIO_MAX;
222 unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) {
223 confess
"setpriority failed: $!
";
228 <dt><strong><a name=
"item_untie_this_x_3cuntie_3e">UNTIE this
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>
237 <dt><strong><a name=
"item_destroy_this_x_3cdestroy_3e">DESTROY this
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>
250 confess
"wrong type
" unless ref $self;
251 carp
"[ Nice::DESTROY pid $$self ]
" if $Nice::DEBUG;
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>
262 <h2><a name=
"tying_arrays_x_array__tying_">Tying Arrays
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>
281 tie @array, 'FixedElem_Array',
3;
282 $array[
0] = 'cat'; # ok.
283 $array[
1] = 'dogs'; # exception, length('dogs')
> 3.
</pre>
284 <p>The preamble code for the class is as follows:
</p>
286 package FixedElem_Array;
290 <dt><strong><a name=
"item_tiearray_classname_2c_list_x_3ctiearray_3e">TIEARRAY classname, LIST
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>
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>
311 my $elemsize = shift;
312 if ( @_ || $elemsize =~ /\D/ ) {
313 croak
"usage: tie ARRAY, '
" . __PACKAGE__ .
"', elem_size
";
316 ELEMSIZE =
> $elemsize,
322 <dt><strong><a name=
"item_fetch_this_2c_index_x_3cfetch_3e">FETCH this, index
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>
335 return $self-
>{ARRAY}-
>[$index];
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>
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>
353 <dt><strong><a name=
"item_store_this_2c_index_2c_value_x_3cstore_3e">STORE this, index, value
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
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-
>{ELEMSIZE}
</code> number of
364 spaces so we have a little more work to do here:
</p>
370 my( $index, $value ) = @_;
371 if ( length $value
> $self-
>{ELEMSIZE} ) {
372 croak
"length of $value is greater than $self-
>{ELEMSIZE}
";
375 $self-
>EXTEND( $index ) if $index
> $self-
>FETCHSIZE();
376 # right justify to keep element size for smaller elements
377 $self-
>{ARRAY}-
>[$index] = sprintf
"%$self-
>{ELEMSIZE}s
", $value;
381 <p>Negative indexes are treated the same as with FETCH.
</p>
384 <dt><strong><a name=
"item_fetchsize_this_x_3cfetchsize_3e">FETCHSIZE this
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>
395 return scalar @{$self-
>{ARRAY}};
399 <dt><strong><a name=
"item_storesize_this_2c_count_x_3cstoresize_3e">STORESIZE this, count
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
410 <p>In our example, 'undef' is really an element containing
411 <code>$self-
>{ELEMSIZE}
</code> number of spaces. Observe:
</p>
418 if ( $count
> $self-
>FETCHSIZE() ) {
419 foreach ( $count - $self-
>FETCHSIZE() .. $count ) {
420 $self-
>STORE( $_, '' );
422 } elsif ( $count
< $self-
>FETCHSIZE() ) {
423 foreach (
0 .. $self-
>FETCHSIZE() - $count -
2 ) {
430 <dt><strong><a name=
"item_extend_this_2c_count_x_3cextend_3e">EXTEND this, count
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>
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
447 $self-
>STORESIZE( $count );
451 <dt><strong><a name=
"item_exists_this_2c_key_x_3cexists_3e">EXISTS this, key
455 <p>Verify that the element at index
<em>key
</em> exists in the tied array
<em>this
</em>.
</p>
458 <p>In our example, we will determine that if an element consists of
459 <code>$self-
>{ELEMSIZE}
</code> spaces only, it does not exist:
</p>
466 return
0 if ! defined $self-
>{ARRAY}-
>[$index] ||
467 $self-
>{ARRAY}-
>[$index] eq ' ' x $self-
>{ELEMSIZE};
472 <dt><strong><a name=
"item_delete_this_2c_key_x_3cdelete_3e">DELETE this, key
476 <p>Delete the element at index
<em>key
</em> from the tied array
<em>this
</em>.
</p>
479 <p>In our example, a deleted item is
<code>$self-
>{ELEMSIZE}
</code> spaces:
</p>
486 return $self-
>STORE( $index, '' );
490 <dt><strong><a name=
"item_clear_this_x_3cclear_3e">CLEAR this
494 <p>Clear (remove, delete, ...) all values from the tied array associated with
495 object
<em>this
</em>. For example:
</p>
501 return $self-
>{ARRAY} = [];
505 <dt><strong><a name=
"item_push_this_2c_list_x_3cpush_3e">PUSH this, LIST
509 <p>Append elements of
<em>LIST
</em> to the array. For example:
</p>
516 my $last = $self-
>FETCHSIZE();
517 $self-
>STORE( $last + $_, $list[$_] ) foreach
0 .. $#list;
518 return $self-
>FETCHSIZE();
522 <dt><strong><a name=
"item_pop_this_x_3cpop_3e">POP this
526 <p>Remove last element of the array and return it. For example:
</p>
532 return pop @{$self-
>{ARRAY}};
536 <dt><strong><a name=
"item_shift_this_x_3cshift_3e">SHIFT this
540 <p>Remove the first element of the array (shifting other elements down)
541 and return it. For example:
</p>
547 return shift @{$self-
>{ARRAY}};
551 <dt><strong><a name=
"item_unshift_this_2c_list_x_3cunshift_3e">UNSHIFT this, LIST
555 <p>Insert LIST elements at the beginning of the array, moving existing elements
556 up to make room. For example:
</p>
563 my $size = scalar( @list );
564 # make room for our list
565 @{$self-
>{ARRAY}}[ $size .. $#{$self-
>{ARRAY}} + $size ]
566 = @{$self-
>{ARRAY}};
567 $self-
>STORE( $_, $list[$_] ) foreach
0 .. $#list;
571 <dt><strong><a name=
"item_splice_this_2c_offset_2c_length_2c_list_x_3csplice">SPLICE this, offset, length, LIST
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>
578 <p><em>offset
</em> is optional and defaults to zero, negative values count back
579 from the end of the array.
</p>
582 <p><em>length
</em> is optional and defaults to rest of the array.
</p>
585 <p><em>LIST
</em> may be empty.
</p>
588 <p>Returns a list of the original
<em>length
</em> elements at
<em>offset
</em>.
</p>
591 <p>In our example, we'll use a little shortcut if there is a
<em>LIST
</em>:
</p>
597 my $offset = shift ||
0;
598 my $length = shift || $self-
>FETCHSIZE() - $offset;
601 tie @list, __PACKAGE__, $self-
>{ELEMSIZE};
604 return splice @{$self-
>{ARRAY}}, $offset, $length, @list;
608 <dt><strong>UNTIE this
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>
615 <dt><strong>DESTROY this
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>
628 <h2><a name=
"tying_hashes_x_hash__tying_">Tying Hashes
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>
652 tie %dot, 'DotFiles';
653 if ( $dot{profile} =~ /MANPATH/ ||
654 $dot{login} =~ /MANPATH/ ||
655 $dot{cshrc} =~ /MANPATH/ )
657 print
"you seem to set your MANPATH\n
";
659 <p>Or here's another sample of using our tied class:
</p>
661 tie %him, 'DotFiles', 'daemon';
662 foreach $f ( keys %him ) {
663 printf
"daemon dot file %s is size %d\n
",
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>
671 <dt><strong><a name=
"item_user">USER
</a></strong>
674 <p>whose dot files this object represents
</p>
677 <dt><strong><a name=
"item_home">HOME
</a></strong>
680 <p>where those dot files live
</p>
683 <dt><strong><a name=
"item_clobber">CLOBBER
</a></strong>
686 <p>whether we should try to change or remove those dot files
</p>
689 <dt><strong><a name=
"item_list">LIST
</a></strong>
692 <p>the hash of dot file names and content mappings
</p>
696 <p>Here's the start of
<em>Dotfiles.pm
</em>:
</p>
700 sub whowasi { (caller(
1))[
3] . '()' }
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
707 <p>Here are the methods for the DotFiles tied hash.
</p>
709 <dt><strong><a name=
"item_tiehash_classname_2c_list_x_3ctiehash_3e">TIEHASH classname, LIST
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>
718 <p>Here's the constructor:
</p>
724 my $user = shift || $
>;
725 my $dotdir = shift || '';
726 croak
"usage: @{[
&whowasi]} [USER [DOTDIR]]
" if @_;
727 $user = getpwuid($user) if $user =~ /^\d+$/;
728 my $dir = (getpwnam($user))[
7]
729 || croak
"@{[
&whowasi]}: no user $user
";
730 $dir .=
"/$dotdir
" if $dotdir;
</pre>
744 || croak
"@{[
&whowasi]}: can't opendir $dir: $!
";
745 foreach $dot ( grep /^\./
&& -f
"$dir/$_
", readdir(DIR)) {
747 $node-
>{LIST}{$dot} = undef;
750 return bless $node, $self;
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>
760 <dt><strong><a name=
"item_fetch_this_2c_key_x_3cfetch_3e">FETCH this, key
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>
769 <p>Here's the fetch for our DotFiles example.
</p>
774 carp
&whowasi if $DEBUG;
777 my $dir = $self-
>{HOME};
778 my $file =
"$dir/.$dot
";
</pre>
782 unless (exists $self-
>{LIST}-
>{$dot} || -f $file) {
783 carp
"@{[
&whowasi]}: no $dot file
" if $DEBUG;
789 if (defined $self-
>{LIST}-
>{$dot}) {
790 return $self-
>{LIST}-
>{$dot};
792 return $self-
>{LIST}-
>{$dot} = `cat $dir/.$dot`;
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>
803 <dt><strong><a name=
"item_store_this_2c_key_2c_value_x_3cstore_3e">STORE this, key, value
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
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>
820 carp
&whowasi if $DEBUG;
824 my $file = $self-
>{HOME} .
"/.$dot
";
825 my $user = $self-
>{USER};
</pre>
829 croak
"@{[
&whowasi]}: $file not clobberable
"
830 unless $self-
>{CLOBBER};
</pre>
834 open(F,
"> $file
") || croak
"can't open $file: $!
";
840 <p>If they wanted to clobber something, they might say:
</p>
844 $ob = tie %daemon_dots, 'daemon';
846 $daemon_dots{signature} =
"A true daemon\n
";
</pre>
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
855 tie %daemon_dots, 'daemon';
856 tied(%daemon_dots)-
>clobber(
1);
</pre>
859 <p>The clobber method is simply:
</p>
865 $self-
>{CLOBBER} = @_ ? shift :
1;
869 <dt><strong>DELETE this, key
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>
880 carp
&whowasi if $DEBUG;
</pre>
886 my $file = $self-
>{HOME} .
"/.$dot
";
887 croak
"@{[
&whowasi]}: won't remove file $file
"
888 unless $self-
>{CLOBBER};
889 delete $self-
>{LIST}-
>{$dot};
890 my $success = unlink($file);
891 carp
"@{[
&whowasi]}: can't unlink $file: $!
" unless $success;
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>
903 <dt><strong>CLEAR this
907 <p>This method is triggered when the whole hash is to be cleared, usually by
908 assigning the empty list to it.
</p>
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>
918 carp
&whowasi if $DEBUG;
920 croak
"@{[
&whowasi]}: won't remove all dot files for $self-
>{USER}
"
921 unless $self-
>{CLOBBER}
> 1;
923 foreach $dot ( keys %{$self-
>{LIST}}) {
924 $self-
>DELETE($dot);
929 <dt><strong>EXISTS this, key
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>
940 carp
&whowasi if $DEBUG;
943 return exists $self-
>{LIST}-
>{$dot};
947 <dt><strong><a name=
"item_firstkey_this_x_3cfirstkey_3e">FIRSTKEY this
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>
958 carp
&whowasi if $DEBUG;
960 my $a = keys %{$self-
>{LIST}}; # reset each() iterator
961 each %{$self-
>{LIST}}
965 <dt><strong><a name=
"item_nextkey_this_2c_lastkey_x_3cnextkey_3e">NEXTKEY this, lastkey
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>
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>
981 carp
&whowasi if $DEBUG;
983 return each %{ $self-
>{LIST} }
987 <dt><strong><a name=
"item_scalar_this_x_3cscalar_3e">SCALAR this
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>
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>
1007 <p>In our example we can just call
<code>scalar
</code> on the underlying hash
1008 referenced by
<code>$self-
>{LIST}
</code>:
</p>
1013 carp
&whowasi if $DEBUG;
1015 return scalar %{ $self-
>{LIST} }
1019 <dt><strong>UNTIE this
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>
1026 <dt><strong>DESTROY this
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>
1037 carp
&whowasi if $DEBUG;
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>
1046 # print out history file offsets
1048 tie(%HIST, 'NDBM_File', '/usr/lib/news/history',
1,
0);
1049 while (($key,$val) = each %HIST) {
1050 print $key, ' = ', unpack('L',$val),
"\n
";
1055 <h2><a name=
"tying_filehandles_x_filehandle__tying_">Tying FileHandles
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>
1074 package Shout;
</pre>
1076 <dt><strong><a name=
"item_tiehandle_classname_2c_list_x_3ctiehandle_3e">TIEHANDLE classname, LIST
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>
1086 sub TIEHANDLE { print
"<shout
>\n
"; my $i; bless \$i, shift }
</pre>
1089 <dt><strong><a name=
"item_write_this_2c_list_x_3cwrite_3e">WRITE this, LIST
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>
1100 my($buf,$len,$offset) = @_;
1101 print
"WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset
";
1105 <dt><strong><a name=
"item_print_this_2c_list_x_3cprint_3e">PRINT this, LIST
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>
1116 sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
</pre>
1119 <dt><strong><a name=
"item_printf_this_2c_list_x_3cprintf_3e">PRINTF this, LIST
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>
1133 print sprintf($fmt, @_);
1137 <dt><strong><a name=
"item_read_this_2c_list_x_3cread_3e">READ this, LIST
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>
1148 my $bufref = \$_[
0];
1149 my(undef,$len,$offset) = @_;
1150 print
"READ called, \$buf=$bufref, \$len=$len, \$offset=$offset
";
1151 # add to $$bufref, set $len to number of characters read
1156 <dt><strong><a name=
"item_readline_this_x_3creadline_3e">READLINE this
1160 <p>This method will be called when the handle is read from via
<HANDLE
>.
1161 The method should return undef when there is no more data.
</p>
1165 sub READLINE { $r = shift;
"READLINE called $$r times\n
"; }
</pre>
1168 <dt><strong><a name=
"item_getc_this_x_3cgetc_3e">GETC this
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>
1176 sub GETC { print
"Don't GETC, Get Perl
"; return
"a
"; }
</pre>
1179 <dt><strong><a name=
"item_close_this_x_3cclose_3e">CLOSE this
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>
1188 sub CLOSE { print
"CLOSE called.\n
" }
</pre>
1191 <dt><strong>UNTIE this
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>
1200 <dt><strong>DESTROY this
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>
1210 sub DESTROY { print
"</shout
>\n
" }
</pre>
1214 <p>Here's how to use our little example:
</p>
1217 print FOO
"hello\n
";
1219 print FOO $a,
" plus
", $b,
" equals
", $a + $b,
"\n
";
1220 print
<FOO
>;
</pre>
1223 <h2><a name=
"untie_this_x_untie_">UNTIE this
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>
1229 <h2><a name=
"the_untie_gotcha_x_untie_">The
<code>untie
</code> Gotcha
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
1238 package Remember;
</pre>
1246 my $filename = shift;
1247 my $handle = new IO::File
"> $filename
"
1248 or die
"Cannot open $filename: $!\n
";
</pre>
1250 print $handle
"The Start\n
";
1251 bless {FH =
> $handle, Value =
> 0}, $class;
1256 return $self-
>{Value};
1262 my $handle = $self-
>{FH};
1263 print $handle
"$value\n
";
1264 $self-
>{Value} = $value;
1269 my $handle = $self-
>{FH};
1270 print $handle
"The End\n
";
1275 <p>Here is an example that makes use of this tie:
</p>
1281 tie $fred, 'Remember', 'myfile.txt';
1286 system
"cat myfile.txt
";
</pre>
1287 <p>This is the output when it is executed:
</p>
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>
1302 my $handle = $self-
>{FH};
1303 print $handle $text,
"\n
";
1305 <p>And here is the previous example modified to use the
<code>comment
</code> method
1306 (which requires the tied object):
</p>
1312 $x = tie $fred, 'Remember', 'myfile.txt';
1315 comment $x
"changing...
";
1318 system
"cat myfile.txt
";
</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>
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
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
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
1362 my ($obj,$count) = @_;
1363 carp
"untie attempted while $count inner references still exist
" if $count;
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>
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>
1401 <h1><a name=
"author">AUTHOR
</a></h1>
1402 <p>Tom Christiansen
</p>
1403 <p>TIEHANDLE by Sven Verdoolaege
<<em><a href=
"mailto:skimo@dns.ufsia.ac.be">skimo@dns.ufsia.ac.be
</a></em>> and Doug MacEachern
<<em><a href=
"mailto:dougm@osf.org">dougm@osf.org
</a></em>></p>
1404 <p>UNTIE by Nick Ing-Simmons
<<em><a href=
"mailto:nick@ing-simmons.net">nick@ing-simmons.net
</a></em>></p>
1405 <p>SCALAR by Tassilo von Parseval
<<em><a href=
"mailto:tassilo.von.parseval@rwth-aachen.de">tassilo.von.parseval@rwth-aachen.de
</a></em>></p>
1406 <p>Tying Arrays by Casey West
<<em><a href=
"mailto:casey@geeknest.com">casey@geeknest.com
</a></em>></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"> perltie - how to hide an object class in a simple variable
</span></strong></big>