.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLTIE 1" .TH PERLTIE 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide" .SH "NAME" perltie \- how to hide an object class in a simple variable .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& tie VARIABLE, CLASSNAME, LIST .Ve .PP .Vb 1 \& $object = tied VARIABLE .Ve .PP .Vb 1 \& untie VARIABLE .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" Prior to release 5.0 of Perl, a programmer could use \fIdbmopen()\fR to connect an on-disk database in the standard Unix \fIdbm\fR\|(3x) format magically to a \f(CW%HASH\fR in their program. However, their Perl was either built with one particular dbm library or another, but not both, and you couldn't extend this mechanism to other packages or types of variables. .PP Now you can. .PP The \fItie()\fR function binds a variable to a class (package) that will provide the implementation for access methods for that variable. Once this magic has been performed, accessing a tied variable automatically triggers method calls in the proper class. The complexity of the class is hidden behind magic methods calls. The method names are in \s-1ALL\s0 \s-1CAPS\s0, which is a convention that Perl uses to indicate that they're called implicitly rather than explicitly\*(--just like the \s-1\fIBEGIN\s0()\fR and \s-1\fIEND\s0()\fR functions. .PP In the \fItie()\fR call, \f(CW\*(C`VARIABLE\*(C'\fR is the name of the variable to be enchanted. \f(CW\*(C`CLASSNAME\*(C'\fR is the name of a class implementing objects of the correct type. Any additional arguments in the \f(CW\*(C`LIST\*(C'\fR are passed to the appropriate constructor method for that class\*(--meaning \s-1\fITIESCALAR\s0()\fR, \&\s-1\fITIEARRAY\s0()\fR, \s-1\fITIEHASH\s0()\fR, or \s-1\fITIEHANDLE\s0()\fR. (Typically these are arguments such as might be passed to the \fIdbminit()\fR function of C.) The object returned by the \*(L"new\*(R" method is also returned by the \fItie()\fR function, which would be useful if you wanted to access other methods in \&\f(CW\*(C`CLASSNAME\*(C'\fR. (You don't actually have to return a reference to a right \&\*(L"type\*(R" (e.g., \s-1HASH\s0 or \f(CW\*(C`CLASSNAME\*(C'\fR) so long as it's a properly blessed object.) You can also retrieve a reference to the underlying object using the \fItied()\fR function. .PP Unlike \fIdbmopen()\fR, the \fItie()\fR function will not \f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR a module for you\*(--you need to do that explicitly yourself. .Sh "Tying Scalars" .IX Subsection "Tying Scalars" A class implementing a tied scalar should define the following methods: \&\s-1TIESCALAR\s0, \s-1FETCH\s0, \s-1STORE\s0, and possibly \s-1UNTIE\s0 and/or \s-1DESTROY\s0. .PP Let's look at each in turn, using as an example a tie class for scalars that allows the user to do something like: .PP .Vb 2 \& tie $his_speed, 'Nice', getppid(); \& tie $my_speed, 'Nice', $$; .Ve .PP And now whenever either of those variables is accessed, its current system priority is retrieved and returned. If those variables are set, then the process's priority is changed! .PP We'll use Jarkko Hietaniemi <\fIjhi@iki.fi\fR>'s BSD::Resource class (not included) to access the \s-1PRIO_PROCESS\s0, \s-1PRIO_MIN\s0, and \s-1PRIO_MAX\s0 constants from your system, as well as the \fIgetpriority()\fR and \fIsetpriority()\fR system calls. Here's the preamble of the class. .PP .Vb 5 \& package Nice; \& use Carp; \& use BSD::Resource; \& use strict; \& $Nice::DEBUG = 0 unless defined $Nice::DEBUG; .Ve .IP "\s-1TIESCALAR\s0 classname, \s-1LIST\s0" 4 .IX Item "TIESCALAR classname, LIST" This is the constructor for the class. That means it is expected to return a blessed reference to a new scalar (probably anonymous) that it's creating. For example: .Sp .Vb 3 \& sub TIESCALAR { \& my $class = shift; \& my $pid = shift || $$; # 0 means me .Ve .Sp .Vb 4 \& if ($pid !~ /^\ed+$/) { \& carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W; \& return undef; \& } .Ve .Sp .Vb 4 \& unless (kill 0, $pid) { # EPERM or ERSCH, no doubt \& carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W; \& return undef; \& } .Ve .Sp .Vb 2 \& return bless \e$pid, $class; \& } .Ve .Sp This tie class has chosen to return an error rather than raising an exception if its constructor should fail. While this is how \fIdbmopen()\fR works, other classes may well not wish to be so forgiving. It checks the global variable \f(CW$^W\fR to see whether to emit a bit of noise anyway. .IP "\s-1FETCH\s0 this" 4 .IX Item "FETCH this" This method will be triggered every time the tied variable is accessed (read). It takes no arguments beyond its self reference, which is the object representing the scalar we're dealing with. Because in this case we're using just a \s-1SCALAR\s0 ref for the tied scalar object, a simple $$self allows the method to get at the real value stored there. In our example below, that real value is the process \s-1ID\s0 to which we've tied our variable. .Sp .Vb 10 \& sub FETCH { \& my $self = shift; \& confess "wrong type" unless ref $self; \& croak "usage error" if @_; \& my $nicety; \& local($!) = 0; \& $nicety = getpriority(PRIO_PROCESS, $$self); \& if ($!) { croak "getpriority failed: $!" } \& return $nicety; \& } .Ve .Sp This time we've decided to blow up (raise an exception) if the renice fails\*(--there's no place for us to return an error otherwise, and it's probably the right thing to do. .IP "\s-1STORE\s0 this, value" 4 .IX Item "STORE this, value" This method will be triggered every time the tied variable is set (assigned). Beyond its self reference, it also expects one (and only one) argument\*(--the new value the user is trying to assign. .Sp .Vb 5 \& sub STORE { \& my $self = shift; \& confess "wrong type" unless ref $self; \& my $new_nicety = shift; \& croak "usage error" if @_; .Ve .Sp .Vb 6 \& if ($new_nicety < PRIO_MIN) { \& carp sprintf \& "WARNING: priority %d less than minimum system priority %d", \& $new_nicety, PRIO_MIN if $^W; \& $new_nicety = PRIO_MIN; \& } .Ve .Sp .Vb 6 \& if ($new_nicety > PRIO_MAX) { \& carp sprintf \& "WARNING: priority %d greater than maximum system priority %d", \& $new_nicety, PRIO_MAX if $^W; \& $new_nicety = PRIO_MAX; \& } .Ve .Sp .Vb 5 \& unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) { \& confess "setpriority failed: $!"; \& } \& return $new_nicety; \& } .Ve .IP "\s-1UNTIE\s0 this" 4 .IX Item "UNTIE this" This method will be triggered when the \f(CW\*(C`untie\*(C'\fR occurs. This can be useful if the class needs to know when no further calls will be made. (Except \s-1DESTROY\s0 of course.) See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below for more details. .IP "\s-1DESTROY\s0 this" 4 .IX Item "DESTROY this" This method will be triggered when the tied variable needs to be destructed. As with other object classes, such a method is seldom necessary, because Perl deallocates its moribund object's memory for you automatically\*(--this isn't \&\*(C+, you know. We'll use a \s-1DESTROY\s0 method here for debugging purposes only. .Sp .Vb 5 \& sub DESTROY { \& my $self = shift; \& confess "wrong type" unless ref $self; \& carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG; \& } .Ve .PP That's about all there is to it. Actually, it's more than all there is to it, because we've done a few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler \&\s-1TIESCALAR\s0 classes are certainly possible. .Sh "Tying Arrays" .IX Subsection "Tying Arrays" A class implementing a tied ordinary array should define the following methods: \s-1TIEARRAY\s0, \s-1FETCH\s0, \s-1STORE\s0, \s-1FETCHSIZE\s0, \s-1STORESIZE\s0 and perhaps \s-1UNTIE\s0 and/or \s-1DESTROY\s0. .PP \&\s-1FETCHSIZE\s0 and \s-1STORESIZE\s0 are used to provide \f(CW$#array\fR and equivalent \f(CW\*(C`scalar(@array)\*(C'\fR access. .PP The methods \s-1POP\s0, \s-1PUSH\s0, \s-1SHIFT\s0, \s-1UNSHIFT\s0, \s-1SPLICE\s0, \s-1DELETE\s0, and \s-1EXISTS\s0 are required if the perl operator with the corresponding (but lowercase) name is to operate on the tied array. The \fBTie::Array\fR class can be used as a base class to implement the first five of these in terms of the basic methods above. The default implementations of \s-1DELETE\s0 and \s-1EXISTS\s0 in \&\fBTie::Array\fR simply \f(CW\*(C`croak\*(C'\fR. .PP In addition \s-1EXTEND\s0 will be called when perl would have pre-extended allocation in a real array. .PP For this discussion, we'll implement an array whose elements are a fixed size at creation. If you try to create an element larger than the fixed size, you'll take an exception. For example: .PP .Vb 4 \& use FixedElem_Array; \& tie @array, 'FixedElem_Array', 3; \& $array[0] = 'cat'; # ok. \& $array[1] = 'dogs'; # exception, length('dogs') > 3. .Ve .PP The preamble code for the class is as follows: .PP .Vb 3 \& package FixedElem_Array; \& use Carp; \& use strict; .Ve .IP "\s-1TIEARRAY\s0 classname, \s-1LIST\s0" 4 .IX Item "TIEARRAY classname, LIST" This is the constructor for the class. That means it is expected to return a blessed reference through which the new array (probably an anonymous \s-1ARRAY\s0 ref) will be accessed. .Sp In our example, just to show you that you don't \fIreally\fR have to return an \&\s-1ARRAY\s0 reference, we'll choose a \s-1HASH\s0 reference to represent our object. A \s-1HASH\s0 works out well as a generic record type: the \f(CW\*(C`{ELEMSIZE}\*(C'\fR field will store the maximum element size allowed, and the \f(CW\*(C`{ARRAY}\*(C'\fR field will hold the true \s-1ARRAY\s0 ref. If someone outside the class tries to dereference the object returned (doubtless thinking it an \s-1ARRAY\s0 ref), they'll blow up. This just goes to show you that you should respect an object's privacy. .Sp .Vb 11 \& sub TIEARRAY { \& my $class = shift; \& my $elemsize = shift; \& if ( @_ || $elemsize =~ /\eD/ ) { \& croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size"; \& } \& return bless { \& ELEMSIZE => $elemsize, \& ARRAY => [], \& }, $class; \& } .Ve .IP "\s-1FETCH\s0 this, index" 4 .IX Item "FETCH this, index" This method will be triggered every time an individual element the tied array is accessed (read). It takes one argument beyond its self reference: the index whose value we're trying to fetch. .Sp .Vb 5 \& sub FETCH { \& my $self = shift; \& my $index = shift; \& return $self->{ARRAY}->[$index]; \& } .Ve .Sp If a negative array index is used to read from an array, the index will be translated to a positive one internally by calling \s-1FETCHSIZE\s0 before being passed to \s-1FETCH\s0. .Sp As you may have noticed, the name of the \s-1FETCH\s0 method (et al.) is the same for all accesses, even though the constructors differ in names (\s-1TIESCALAR\s0 vs \s-1TIEARRAY\s0). While in theory you could have the same class servicing several tied types, in practice this becomes cumbersome, and it's easiest to keep them at simply one tie type per class. .IP "\s-1STORE\s0 this, index, value" 4 .IX Item "STORE this, index, value" This method will be triggered every time an element in the tied array is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something and the value we're trying to put there. .Sp In our example, \f(CW\*(C`undef\*(C'\fR is really \f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR number of spaces so we have a little more work to do here: .Sp .Vb 11 \& sub STORE { \& my $self = shift; \& my( $index, $value ) = @_; \& if ( length $value > $self->{ELEMSIZE} ) { \& croak "length of $value is greater than $self->{ELEMSIZE}"; \& } \& # fill in the blanks \& $self->EXTEND( $index ) if $index > $self->FETCHSIZE(); \& # right justify to keep element size for smaller elements \& $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value; \& } .Ve .Sp Negative indexes are treated the same as with \s-1FETCH\s0. .IP "\s-1FETCHSIZE\s0 this" 4 .IX Item "FETCHSIZE this" Returns the total number of items in the tied array associated with object \fIthis\fR. (Equivalent to \f(CW\*(C`scalar(@array)\*(C'\fR). For example: .Sp .Vb 4 \& sub FETCHSIZE { \& my $self = shift; \& return scalar @{$self->{ARRAY}}; \& } .Ve .IP "\s-1STORESIZE\s0 this, count" 4 .IX Item "STORESIZE this, count" Sets the total number of items in the tied array associated with object \fIthis\fR to be \fIcount\fR. If this makes the array larger then class's mapping of \f(CW\*(C`undef\*(C'\fR should be returned for new positions. If the array becomes smaller then entries beyond count should be deleted. .Sp In our example, 'undef' is really an element containing \&\f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR number of spaces. Observe: .Sp .Vb 13 \& sub STORESIZE { \& my $self = shift; \& my $count = shift; \& if ( $count > $self->FETCHSIZE() ) { \& foreach ( $count - $self->FETCHSIZE() .. $count ) { \& $self->STORE( $_, '' ); \& } \& } elsif ( $count < $self->FETCHSIZE() ) { \& foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) { \& $self->POP(); \& } \& } \& } .Ve .IP "\s-1EXTEND\s0 this, count" 4 .IX Item "EXTEND this, count" Informative call that array is likely to grow to have \fIcount\fR entries. Can be used to optimize allocation. This method need do nothing. .Sp In our example, we want to make sure there are no blank (\f(CW\*(C`undef\*(C'\fR) entries, so \f(CW\*(C`EXTEND\*(C'\fR will make use of \f(CW\*(C`STORESIZE\*(C'\fR to fill elements as needed: .Sp .Vb 5 \& sub EXTEND { \& my $self = shift; \& my $count = shift; \& $self->STORESIZE( $count ); \& } .Ve .IP "\s-1EXISTS\s0 this, key" 4 .IX Item "EXISTS this, key" Verify that the element at index \fIkey\fR exists in the tied array \fIthis\fR. .Sp In our example, we will determine that if an element consists of \&\f(CW\*(C`$self\->{ELEMSIZE}\*(C'\fR spaces only, it does not exist: .Sp .Vb 7 \& sub EXISTS { \& my $self = shift; \& my $index = shift; \& return 0 if ! defined $self->{ARRAY}->[$index] || \& $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE}; \& return 1; \& } .Ve .IP "\s-1DELETE\s0 this, key" 4 .IX Item "DELETE this, key" Delete the element at index \fIkey\fR from the tied array \fIthis\fR. .Sp In our example, a deleted item is \f(CW\*(C`$self\-\*(C'\fR{\s-1ELEMSIZE\s0}> spaces: .Sp .Vb 5 \& sub DELETE { \& my $self = shift; \& my $index = shift; \& return $self->STORE( $index, '' ); \& } .Ve .IP "\s-1CLEAR\s0 this" 4 .IX Item "CLEAR this" Clear (remove, delete, ...) all values from the tied array associated with object \fIthis\fR. For example: .Sp .Vb 4 \& sub CLEAR { \& my $self = shift; \& return $self->{ARRAY} = []; \& } .Ve .IP "\s-1PUSH\s0 this, \s-1LIST\s0" 4 .IX Item "PUSH this, LIST" Append elements of \fI\s-1LIST\s0\fR to the array. For example: .Sp .Vb 7 \& sub PUSH { \& my $self = shift; \& my @list = @_; \& my $last = $self->FETCHSIZE(); \& $self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list; \& return $self->FETCHSIZE(); \& } .Ve .IP "\s-1POP\s0 this" 4 .IX Item "POP this" Remove last element of the array and return it. For example: .Sp .Vb 4 \& sub POP { \& my $self = shift; \& return pop @{$self->{ARRAY}}; \& } .Ve .IP "\s-1SHIFT\s0 this" 4 .IX Item "SHIFT this" Remove the first element of the array (shifting other elements down) and return it. For example: .Sp .Vb 4 \& sub SHIFT { \& my $self = shift; \& return shift @{$self->{ARRAY}}; \& } .Ve .IP "\s-1UNSHIFT\s0 this, \s-1LIST\s0" 4 .IX Item "UNSHIFT this, LIST" Insert \s-1LIST\s0 elements at the beginning of the array, moving existing elements up to make room. For example: .Sp .Vb 9 \& sub UNSHIFT { \& my $self = shift; \& my @list = @_; \& my $size = scalar( @list ); \& # make room for our list \& @{$self->{ARRAY}}[ $size .. $#{$self->{ARRAY}} + $size ] \& = @{$self->{ARRAY}}; \& $self->STORE( $_, $list[$_] ) foreach 0 .. $#list; \& } .Ve .IP "\s-1SPLICE\s0 this, offset, length, \s-1LIST\s0" 4 .IX Item "SPLICE this, offset, length, LIST" Perform the equivalent of \f(CW\*(C`splice\*(C'\fR on the array. .Sp \&\fIoffset\fR is optional and defaults to zero, negative values count back from the end of the array. .Sp \&\fIlength\fR is optional and defaults to rest of the array. .Sp \&\fI\s-1LIST\s0\fR may be empty. .Sp Returns a list of the original \fIlength\fR elements at \fIoffset\fR. .Sp In our example, we'll use a little shortcut if there is a \fI\s-1LIST\s0\fR: .Sp .Vb 11 \& sub SPLICE { \& my $self = shift; \& my $offset = shift || 0; \& my $length = shift || $self->FETCHSIZE() - $offset; \& my @list = (); \& if ( @_ ) { \& tie @list, __PACKAGE__, $self->{ELEMSIZE}; \& @list = @_; \& } \& return splice @{$self->{ARRAY}}, $offset, $length, @list; \& } .Ve .IP "\s-1UNTIE\s0 this" 4 .IX Item "UNTIE this" Will be called when \f(CW\*(C`untie\*(C'\fR happens. (See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below.) .IP "\s-1DESTROY\s0 this" 4 .IX Item "DESTROY this" This method will be triggered when the tied variable needs to be destructed. As with the scalar tie class, this is almost never needed in a language that does its own garbage collection, so this time we'll just leave it out. .Sh "Tying Hashes" .IX Subsection "Tying Hashes" Hashes were the first Perl data type to be tied (see \fIdbmopen()\fR). A class implementing a tied hash should define the following methods: \s-1TIEHASH\s0 is the constructor. \s-1FETCH\s0 and \s-1STORE\s0 access the key and value pairs. \s-1EXISTS\s0 reports whether a key is present in the hash, and \s-1DELETE\s0 deletes one. \&\s-1CLEAR\s0 empties the hash by deleting all the key and value pairs. \s-1FIRSTKEY\s0 and \s-1NEXTKEY\s0 implement the \fIkeys()\fR and \fIeach()\fR functions to iterate over all the keys. \s-1UNTIE\s0 is called when \f(CW\*(C`untie\*(C'\fR happens, and \s-1DESTROY\s0 is called when the tied variable is garbage collected. .PP If this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash module for most of your methods, redefining only the interesting ones. See Tie::Hash for details. .PP Remember that Perl distinguishes between a key not existing in the hash, and the key existing in the hash but having a corresponding value of \&\f(CW\*(C`undef\*(C'\fR. The two possibilities can be tested with the \f(CW\*(C`exists()\*(C'\fR and \&\f(CW\*(C`defined()\*(C'\fR functions. .PP Here's an example of a somewhat interesting tied hash class: it gives you a hash representing a particular user's dot files. You index into the hash with the name of the file (minus the dot) and you get back that dot file's contents. For example: .PP .Vb 8 \& use DotFiles; \& tie %dot, 'DotFiles'; \& if ( $dot{profile} =~ /MANPATH/ || \& $dot{login} =~ /MANPATH/ || \& $dot{cshrc} =~ /MANPATH/ ) \& { \& print "you seem to set your MANPATH\en"; \& } .Ve .PP Or here's another sample of using our tied class: .PP .Vb 5 \& tie %him, 'DotFiles', 'daemon'; \& foreach $f ( keys %him ) { \& printf "daemon dot file %s is size %d\en", \& $f, length $him{$f}; \& } .Ve .PP In our tied hash DotFiles example, we use a regular hash for the object containing several important fields, of which only the \f(CW\*(C`{LIST}\*(C'\fR field will be what the user thinks of as the real hash. .IP "\s-1USER\s0" 5 .IX Item "USER" whose dot files this object represents .IP "\s-1HOME\s0" 5 .IX Item "HOME" where those dot files live .IP "\s-1CLOBBER\s0" 5 .IX Item "CLOBBER" whether we should try to change or remove those dot files .IP "\s-1LIST\s0" 5 .IX Item "LIST" the hash of dot file names and content mappings .PP Here's the start of \fIDotfiles.pm\fR: .PP .Vb 5 \& package DotFiles; \& use Carp; \& sub whowasi { (caller(1))[3] . '()' } \& my $DEBUG = 0; \& sub debug { $DEBUG = @_ ? shift : 1 } .Ve .PP For our example, we want to be able to emit debugging info to help in tracing during development. We keep also one convenience function around internally to help print out warnings; \fIwhowasi()\fR returns the function name that calls it. .PP Here are the methods for the DotFiles tied hash. .IP "\s-1TIEHASH\s0 classname, \s-1LIST\s0" 4 .IX Item "TIEHASH classname, LIST" This is the constructor for the class. That means it is expected to return a blessed reference through which the new object (probably but not necessarily an anonymous hash) will be accessed. .Sp Here's the constructor: .Sp .Vb 9 \& sub TIEHASH { \& my $self = shift; \& my $user = shift || $>; \& my $dotdir = shift || ''; \& croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_; \& $user = getpwuid($user) if $user =~ /^\ed+$/; \& my $dir = (getpwnam($user))[7] \& || croak "@{[&whowasi]}: no user $user"; \& $dir .= "/$dotdir" if $dotdir; .Ve .Sp .Vb 6 \& my $node = { \& USER => $user, \& HOME => $dir, \& LIST => {}, \& CLOBBER => 0, \& }; .Ve .Sp .Vb 9 \& opendir(DIR, $dir) \& || croak "@{[&whowasi]}: can't opendir $dir: $!"; \& foreach $dot ( grep /^\e./ && -f "$dir/$_", readdir(DIR)) { \& $dot =~ s/^\e.//; \& $node->{LIST}{$dot} = undef; \& } \& closedir DIR; \& return bless $node, $self; \& } .Ve .Sp It's probably worth mentioning that if you're going to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't \fIchdir()\fR there, it would have been testing the wrong file. .IP "\s-1FETCH\s0 this, key" 4 .IX Item "FETCH this, key" This method will be triggered every time an element in the tied hash is accessed (read). It takes one argument beyond its self reference: the key whose value we're trying to fetch. .Sp Here's the fetch for our DotFiles example. .Sp .Vb 6 \& sub FETCH { \& carp &whowasi if $DEBUG; \& my $self = shift; \& my $dot = shift; \& my $dir = $self->{HOME}; \& my $file = "$dir/.$dot"; .Ve .Sp .Vb 4 \& unless (exists $self->{LIST}->{$dot} || -f $file) { \& carp "@{[&whowasi]}: no $dot file" if $DEBUG; \& return undef; \& } .Ve .Sp .Vb 6 \& if (defined $self->{LIST}->{$dot}) { \& return $self->{LIST}->{$dot}; \& } else { \& return $self->{LIST}->{$dot} = `cat $dir/.$dot`; \& } \& } .Ve .Sp It was easy to write by having it call the Unix \fIcat\fR\|(1) command, but it would probably be more portable to open the file manually (and somewhat more efficient). Of course, because dot files are a Unixy concept, we're not that concerned. .IP "\s-1STORE\s0 this, key, value" 4 .IX Item "STORE this, key, value" This method will be triggered every time an element in the tied hash is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something, and the value we're trying to put there. .Sp Here in our DotFiles example, we'll be careful not to let them try to overwrite the file unless they've called the \fIclobber()\fR method on the original object reference returned by \fItie()\fR. .Sp .Vb 7 \& sub STORE { \& carp &whowasi if $DEBUG; \& my $self = shift; \& my $dot = shift; \& my $value = shift; \& my $file = $self->{HOME} . "/.$dot"; \& my $user = $self->{USER}; .Ve .Sp .Vb 2 \& croak "@{[&whowasi]}: $file not clobberable" \& unless $self->{CLOBBER}; .Ve .Sp .Vb 4 \& open(F, "> $file") || croak "can't open $file: $!"; \& print F $value; \& close(F); \& } .Ve .Sp If they wanted to clobber something, they might say: .Sp .Vb 3 \& $ob = tie %daemon_dots, 'daemon'; \& $ob->clobber(1); \& $daemon_dots{signature} = "A true daemon\en"; .Ve .Sp Another way to lay hands on a reference to the underlying object is to use the \fItied()\fR function, so they might alternately have set clobber using: .Sp .Vb 2 \& tie %daemon_dots, 'daemon'; \& tied(%daemon_dots)->clobber(1); .Ve .Sp The clobber method is simply: .Sp .Vb 4 \& sub clobber { \& my $self = shift; \& $self->{CLOBBER} = @_ ? shift : 1; \& } .Ve .IP "\s-1DELETE\s0 this, key" 4 .IX Item "DELETE this, key" This method is triggered when we remove an element from the hash, typically by using the \fIdelete()\fR function. Again, we'll be careful to check whether they really want to clobber files. .Sp .Vb 2 \& sub DELETE { \& carp &whowasi if $DEBUG; .Ve .Sp .Vb 10 \& my $self = shift; \& my $dot = shift; \& my $file = $self->{HOME} . "/.$dot"; \& croak "@{[&whowasi]}: won't remove file $file" \& unless $self->{CLOBBER}; \& delete $self->{LIST}->{$dot}; \& my $success = unlink($file); \& carp "@{[&whowasi]}: can't unlink $file: $!" unless $success; \& $success; \& } .Ve .Sp The value returned by \s-1DELETE\s0 becomes the return value of the call to \fIdelete()\fR. If you want to emulate the normal behavior of \fIdelete()\fR, you should return whatever \s-1FETCH\s0 would have returned for this key. In this example, we have chosen instead to return a value which tells the caller whether the file was successfully deleted. .IP "\s-1CLEAR\s0 this" 4 .IX Item "CLEAR this" This method is triggered when the whole hash is to be cleared, usually by assigning the empty list to it. .Sp In our example, that would remove all the user's dot files! It's such a dangerous thing that they'll have to set \s-1CLOBBER\s0 to something higher than 1 to make it happen. .Sp .Vb 10 \& sub CLEAR { \& carp &whowasi if $DEBUG; \& my $self = shift; \& croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}" \& unless $self->{CLOBBER} > 1; \& my $dot; \& foreach $dot ( keys %{$self->{LIST}}) { \& $self->DELETE($dot); \& } \& } .Ve .IP "\s-1EXISTS\s0 this, key" 4 .IX Item "EXISTS this, key" This method is triggered when the user uses the \fIexists()\fR function on a particular hash. In our example, we'll look at the \f(CW\*(C`{LIST}\*(C'\fR hash element for this: .Sp .Vb 6 \& sub EXISTS { \& carp &whowasi if $DEBUG; \& my $self = shift; \& my $dot = shift; \& return exists $self->{LIST}->{$dot}; \& } .Ve .IP "\s-1FIRSTKEY\s0 this" 4 .IX Item "FIRSTKEY this" This method will be triggered when the user is going to iterate through the hash, such as via a \fIkeys()\fR or \fIeach()\fR call. .Sp .Vb 6 \& sub FIRSTKEY { \& carp &whowasi if $DEBUG; \& my $self = shift; \& my $a = keys %{$self->{LIST}}; # reset each() iterator \& each %{$self->{LIST}} \& } .Ve .IP "\s-1NEXTKEY\s0 this, lastkey" 4 .IX Item "NEXTKEY this, lastkey" This method gets triggered during a \fIkeys()\fR or \fIeach()\fR iteration. It has a second argument which is the last key that had been accessed. This is useful if you're carrying about ordering or calling the iterator from more than one sequence, or not really storing things in a hash anywhere. .Sp For our example, we're using a real hash so we'll do just the simple thing, but we'll have to go through the \s-1LIST\s0 field indirectly. .Sp .Vb 5 \& sub NEXTKEY { \& carp &whowasi if $DEBUG; \& my $self = shift; \& return each %{ $self->{LIST} } \& } .Ve .IP "\s-1UNTIE\s0 this" 4 .IX Item "UNTIE this" This is called when \f(CW\*(C`untie\*(C'\fR occurs. See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below. .IP "\s-1DESTROY\s0 this" 4 .IX Item "DESTROY this" This method is triggered when a tied hash is about to go out of scope. You don't really need it unless you're trying to add debugging or have auxiliary state to clean up. Here's a very simple function: .Sp .Vb 3 \& sub DESTROY { \& carp &whowasi if $DEBUG; \& } .Ve .PP Note that functions such as \fIkeys()\fR and \fIvalues()\fR may return huge lists when used on large objects, like \s-1DBM\s0 files. You may prefer to use the \&\fIeach()\fR function to iterate over such. Example: .PP .Vb 7 \& # print out history file offsets \& use NDBM_File; \& tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); \& while (($key,$val) = each %HIST) { \& print $key, ' = ', unpack('L',$val), "\en"; \& } \& untie(%HIST); .Ve .Sh "Tying FileHandles" .IX Subsection "Tying FileHandles" This is partially implemented now. .PP A class implementing a tied filehandle should define the following methods: \s-1TIEHANDLE\s0, at least one of \s-1PRINT\s0, \s-1PRINTF\s0, \s-1WRITE\s0, \s-1READLINE\s0, \s-1GETC\s0, \&\s-1READ\s0, and possibly \s-1CLOSE\s0, \s-1UNTIE\s0 and \s-1DESTROY\s0. The class can also provide: \s-1BINMODE\s0, \&\s-1OPEN\s0, \s-1EOF\s0, \s-1FILENO\s0, \s-1SEEK\s0, \s-1TELL\s0 \- if the corresponding perl operators are used on the handle. .PP It is especially useful when perl is embedded in some other program, where output to \s-1STDOUT\s0 and \s-1STDERR\s0 may have to be redirected in some special way. See nvi and the Apache module for examples. .PP In our example we're going to create a shouting handle. .PP .Vb 1 \& package Shout; .Ve .IP "\s-1TIEHANDLE\s0 classname, \s-1LIST\s0" 4 .IX Item "TIEHANDLE classname, LIST" This is the constructor for the class. That means it is expected to return a blessed reference of some sort. The reference can be used to hold some internal information. .Sp .Vb 1 \& sub TIEHANDLE { print "\en"; my $i; bless \e$i, shift } .Ve .IP "\s-1WRITE\s0 this, \s-1LIST\s0" 4 .IX Item "WRITE this, LIST" This method will be called when the handle is written to via the \&\f(CW\*(C`syswrite\*(C'\fR function. .Sp .Vb 5 \& sub WRITE { \& $r = shift; \& my($buf,$len,$offset) = @_; \& print "WRITE called, \e$buf=$buf, \e$len=$len, \e$offset=$offset"; \& } .Ve .IP "\s-1PRINT\s0 this, \s-1LIST\s0" 4 .IX Item "PRINT this, LIST" This method will be triggered every time the tied handle is printed to with the \f(CW\*(C`print()\*(C'\fR function. Beyond its self reference it also expects the list that was passed to the print function. .Sp .Vb 1 \& sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\e } .Ve .IP "\s-1PRINTF\s0 this, \s-1LIST\s0" 4 .IX Item "PRINTF this, LIST" This method will be triggered every time the tied handle is printed to with the \f(CW\*(C`printf()\*(C'\fR function. Beyond its self reference it also expects the format and list that was passed to the printf function. .Sp .Vb 5 \& sub PRINTF { \& shift; \& my $fmt = shift; \& print sprintf($fmt, @_)."\en"; \& } .Ve .IP "\s-1READ\s0 this, \s-1LIST\s0" 4 .IX Item "READ this, LIST" This method will be called when the handle is read from via the \f(CW\*(C`read\*(C'\fR or \f(CW\*(C`sysread\*(C'\fR functions. .Sp .Vb 8 \& sub READ { \& my $self = shift; \& my $bufref = \e$_[0]; \& my(undef,$len,$offset) = @_; \& print "READ called, \e$buf=$bufref, \e$len=$len, \e$offset=$offset"; \& # add to $$bufref, set $len to number of characters read \& $len; \& } .Ve .IP "\s-1READLINE\s0 this" 4 .IX Item "READLINE this" This method will be called when the handle is read from via <\s-1HANDLE\s0>. The method should return undef when there is no more data. .Sp .Vb 1 \& sub READLINE { $r = shift; "READLINE called $$r times\en"; } .Ve .IP "\s-1GETC\s0 this" 4 .IX Item "GETC this" This method will be called when the \f(CW\*(C`getc\*(C'\fR function is called. .Sp .Vb 1 \& sub GETC { print "Don't GETC, Get Perl"; return "a"; } .Ve .IP "\s-1CLOSE\s0 this" 4 .IX Item "CLOSE this" This method will be called when the handle is closed via the \f(CW\*(C`close\*(C'\fR function. .Sp .Vb 1 \& sub CLOSE { print "CLOSE called.\en" } .Ve .IP "\s-1UNTIE\s0 this" 4 .IX Item "UNTIE this" As with the other types of ties, this method will be called when \f(CW\*(C`untie\*(C'\fR happens. It may be appropriate to \*(L"auto \s-1CLOSE\s0\*(R" when this occurs. See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below. .IP "\s-1DESTROY\s0 this" 4 .IX Item "DESTROY this" As with the other types of ties, this method will be called when the tied handle is about to be destroyed. This is useful for debugging and possibly cleaning up. .Sp .Vb 1 \& sub DESTROY { print "\en" } .Ve .PP Here's how to use our little example: .PP .Vb 5 \& tie(*FOO,'Shout'); \& print FOO "hello\en"; \& $a = 4; $b = 6; \& print FOO $a, " plus ", $b, " equals ", $a + $b, "\en"; \& print ; .Ve .Sh "\s-1UNTIE\s0 this" .IX Subsection "UNTIE this" You can define for all tie types an \s-1UNTIE\s0 method that will be called at \fIuntie()\fR. See "The \f(CW\*(C`untie\*(C'\fR Gotcha" below. .ie n .Sh "The ""untie"" Gotcha" .el .Sh "The \f(CWuntie\fP Gotcha" .IX Subsection "The untie Gotcha" If you intend making use of the object returned from either \fItie()\fR or \&\fItied()\fR, and if the tie's target class defines a destructor, there is a subtle gotcha you \fImust\fR guard against. .PP As setup, consider this (admittedly rather contrived) example of a tie; all it does is use a file to keep a log of the values assigned to a scalar. .PP .Vb 1 \& package Remember; .Ve .PP .Vb 3 \& use strict; \& use warnings; \& use IO::File; .Ve .PP .Vb 5 \& sub TIESCALAR { \& my $class = shift; \& my $filename = shift; \& my $handle = new IO::File "> $filename" \& or die "Cannot open $filename: $!\en"; .Ve .PP .Vb 3 \& print $handle "The Start\en"; \& bless {FH => $handle, Value => 0}, $class; \& } .Ve .PP .Vb 4 \& sub FETCH { \& my $self = shift; \& return $self->{Value}; \& } .Ve .PP .Vb 7 \& sub STORE { \& my $self = shift; \& my $value = shift; \& my $handle = $self->{FH}; \& print $handle "$value\en"; \& $self->{Value} = $value; \& } .Ve .PP .Vb 6 \& sub DESTROY { \& my $self = shift; \& my $handle = $self->{FH}; \& print $handle "The End\en"; \& close $handle; \& } .Ve .PP .Vb 1 \& 1; .Ve .PP Here is an example that makes use of this tie: .PP .Vb 2 \& use strict; \& use Remember; .Ve .PP .Vb 7 \& my $fred; \& tie $fred, 'Remember', 'myfile.txt'; \& $fred = 1; \& $fred = 4; \& $fred = 5; \& untie $fred; \& system "cat myfile.txt"; .Ve .PP This is the output when it is executed: .PP .Vb 5 \& The Start \& 1 \& 4 \& 5 \& The End .Ve .PP So far so good. Those of you who have been paying attention will have spotted that the tied object hasn't been used so far. So lets add an extra method to the Remember class to allow comments to be included in the file \*(-- say, something like this: .PP .Vb 6 \& sub comment { \& my $self = shift; \& my $text = shift; \& my $handle = $self->{FH}; \& print $handle $text, "\en"; \& } .Ve .PP And here is the previous example modified to use the \f(CW\*(C`comment\*(C'\fR method (which requires the tied object): .PP .Vb 2 \& use strict; \& use Remember; .Ve .PP .Vb 8 \& my ($fred, $x); \& $x = tie $fred, 'Remember', 'myfile.txt'; \& $fred = 1; \& $fred = 4; \& comment $x "changing..."; \& $fred = 5; \& untie $fred; \& system "cat myfile.txt"; .Ve .PP When this code is executed there is no output. Here's why: .PP When a variable is tied, it is associated with the object which is the return value of the \s-1TIESCALAR\s0, \s-1TIEARRAY\s0, or \s-1TIEHASH\s0 function. This object normally has only one reference, namely, the implicit reference from the tied variable. When \fIuntie()\fR is called, that reference is destroyed. Then, as in the first example above, the object's destructor (\s-1DESTROY\s0) is called, which is normal for objects that have no more valid references; and thus the file is closed. .PP In the second example, however, we have stored another reference to the tied object in \f(CW$x\fR. That means that when \fIuntie()\fR gets called there will still be a valid reference to the object in existence, so the destructor is not called at that time, and thus the file is not closed. The reason there is no output is because the file buffers have not been flushed to disk. .PP Now that you know what the problem is, what can you do to avoid it? Prior to the introduction of the optional \s-1UNTIE\s0 method the only way was the good old \f(CW\*(C`\-w\*(C'\fR flag. Which will spot any instances where you call \&\fIuntie()\fR and there are still valid references to the tied object. If the second script above this near the top \f(CW\*(C`use warnings 'untie'\*(C'\fR or was run with the \f(CW\*(C`\-w\*(C'\fR flag, Perl prints this warning message: .PP .Vb 1 \& untie attempted while 1 inner references still exist .Ve .PP To get the script to work properly and silence the warning make sure there are no valid references to the tied object \fIbefore\fR \fIuntie()\fR is called: .PP .Vb 2 \& undef $x; \& untie $fred; .Ve .PP Now that \s-1UNTIE\s0 exists the class designer can decide which parts of the class functionality are really associated with \f(CW\*(C`untie\*(C'\fR and which with the object being destroyed. What makes sense for a given class depends on whether the inner references are being kept so that non-tie-related methods can be called on the object. But in most cases it probably makes sense to move the functionality that would have been in \s-1DESTROY\s0 to the \s-1UNTIE\s0 method. .PP If the \s-1UNTIE\s0 method exists then the warning above does not occur. Instead the \&\s-1UNTIE\s0 method is passed the count of \*(L"extra\*(R" references and can issue its own warning if appropriate. e.g. to replicate the no \s-1UNTIE\s0 case this method can be used: .PP .Vb 5 \& sub UNTIE \& { \& my ($obj,$count) = @_; \& carp "untie attempted while $count inner references still exist" if $count; \& } .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" See DB_File or Config for some interesting \fItie()\fR implementations. A good starting point for many \fItie()\fR implementations is with one of the modules Tie::Scalar, Tie::Array, Tie::Hash, or Tie::Handle. .SH "BUGS" .IX Header "BUGS" You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but \s-1GDBM\s0 and Berkeley \s-1DB\s0 have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One experimental module that does attempt to address this need partially is the \s-1MLDBM\s0 module. Check your nearest \s-1CPAN\s0 site as described in perlmodlib for source code to \s-1MLDBM\s0. .PP Tied filehandles are still incomplete. \fIsysopen()\fR, \fItruncate()\fR, \&\fIflock()\fR, \fIfcntl()\fR, \fIstat()\fR and \-X can't currently be trapped. .SH "AUTHOR" .IX Header "AUTHOR" Tom Christiansen .PP \&\s-1TIEHANDLE\s0 by Sven Verdoolaege <\fIskimo@dns.ufsia.ac.be\fR> and Doug MacEachern <\fIdougm@osf.org\fR> .PP \&\s-1UNTIE\s0 by Nick Ing-Simmons <\fInick@ing\-simmons.net\fR> .PP Tying Arrays by Casey West <\fIcasey@geeknest.com\fR>