📄 perltie.pod
字号:
=head1 NAMEperltie - how to hide an object class in a simple variable=head1 SYNOPSIS tie VARIABLE, CLASSNAME, LIST $object = tied VARIABLE untie VARIABLE=head1 DESCRIPTIONPrior to release 5.0 of Perl, a programmer could use dbmopen()to connect an on-disk database in the standard Unix dbm(3x)format magically to a %HASH in their program. However, their Perl was eitherbuilt with one particular dbm library or another, but not both, andyou couldn't extend this mechanism to other packages or types of variables.Now you can.The tie() function binds a variable to a class (package) that will providethe implementation for access methods for that variable. Once this magichas been performed, accessing a tied variable automatically triggersmethod calls in the proper class. The complexity of the class ishidden behind magic methods calls. The method names are in ALL CAPS,which is a convention that Perl uses to indicate that they're calledimplicitly rather than explicitly--just like the BEGIN() and END()functions.In the tie() call, C<VARIABLE> is the name of the variable to beenchanted. C<CLASSNAME> is the name of a class implementing objects ofthe correct type. Any additional arguments in the C<LIST> are passed tothe appropriate constructor method for that class--meaning TIESCALAR(),TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are argumentssuch as might be passed to the dbminit() function of C.) The objectreturned by the "new" method is also returned by the tie() function,which would be useful if you wanted to access other methods inC<CLASSNAME>. (You don't actually have to return a reference to a right"type" (e.g., HASH or C<CLASSNAME>) so long as it's a properly blessedobject.) You can also retrieve a reference to the underlying objectusing the tied() function.Unlike dbmopen(), the tie() function will not C<use> or C<require> a modulefor you--you need to do that explicitly yourself.=head2 Tying ScalarsA class implementing a tied scalar should define the following methods:TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.Let's look at each in turn, using as an example a tie class forscalars that allows the user to do something like: tie $his_speed, 'Nice', getppid(); tie $my_speed, 'Nice', $$;And now whenever either of those variables is accessed, its currentsystem priority is retrieved and returned. If those variables are set,then the process's priority is changed!We'll use Jarkko Hietaniemi <F<jhi@iki.fi>>'s BSD::Resource class (notincluded) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constantsfrom your system, as well as the getpriority() and setpriority() systemcalls. Here's the preamble of the class. package Nice; use Carp; use BSD::Resource; use strict; $Nice::DEBUG = 0 unless defined $Nice::DEBUG;=over 4=item TIESCALAR classname, LISTThis is the constructor for the class. That means it isexpected to return a blessed reference to a new scalar(probably anonymous) that it's creating. For example: sub TIESCALAR { my $class = shift; my $pid = shift || $$; # 0 means me if ($pid !~ /^\d+$/) { carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W; return undef; } unless (kill 0, $pid) { # EPERM or ERSCH, no doubt carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W; return undef; } return bless \$pid, $class; }This tie class has chosen to return an error rather than raising anexception if its constructor should fail. While this is how dbmopen() works,other classes may well not wish to be so forgiving. It checks the globalvariable C<$^W> to see whether to emit a bit of noise anyway.=item FETCH thisThis method will be triggered every time the tied variable is accessed(read). It takes no arguments beyond its self reference, which is theobject representing the scalar we're dealing with. Because in this casewe're using just a SCALAR ref for the tied scalar object, a simple $$selfallows the method to get at the real value stored there. In our examplebelow, that real value is the process ID to which we've tied our variable. 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; }This time we've decided to blow up (raise an exception) if the renicefails--there's no place for us to return an error otherwise, and it'sprobably the right thing to do.=item STORE this, valueThis 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. sub STORE { my $self = shift; confess "wrong type" unless ref $self; my $new_nicety = shift; croak "usage error" if @_; 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; } 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; } unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) { confess "setpriority failed: $!"; } return $new_nicety; }=item UNTIE thisThis method will be triggered when the C<untie> occurs. This can be usefulif the class needs to know when no further calls will be made. (Except DESTROYof course.) See below for more details.=item DESTROY thisThis method will be triggered when the tied variable needs to be destructed.As with other object classes, such a method is seldom necessary, because Perldeallocates its moribund object's memory for you automatically--this isn'tC++, you know. We'll use a DESTROY method here for debugging purposes only. sub DESTROY { my $self = shift; confess "wrong type" unless ref $self; carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG; }=backThat's about all there is to it. Actually, it's more than all thereis to it, because we've done a few nice things here for the sakeof completeness, robustness, and general aesthetics. SimplerTIESCALAR classes are certainly possible.=head2 Tying ArraysA class implementing a tied ordinary array should define the followingmethods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY.FETCHSIZE and STORESIZE are used to provide C<$#array> andequivalent C<scalar(@array)> access.The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS arerequired if the perl operator with the corresponding (but lowercase) nameis to operate on the tied array. The B<Tie::Array> class can be used as abase class to implement the first five of these in terms of the basicmethods above. The default implementations of DELETE and EXISTS inB<Tie::Array> simply C<croak>.In addition EXTEND will be called when perl would have pre-extendedallocation in a real array.For this discussion, we'll implement an array whose elements are a fixedsize at creation. If you try to create an element larger than the fixedsize, you'll take an exception. For example: use FixedElem_Array; tie @array, 'FixedElem_Array', 3; $array[0] = 'cat'; # ok. $array[1] = 'dogs'; # exception, length('dogs') > 3.The preamble code for the class is as follows: package FixedElem_Array; use Carp; use strict;=over 4=item TIEARRAY classname, LISTThis is the constructor for the class. That means it is expected toreturn a blessed reference through which the new array (probably ananonymous ARRAY ref) will be accessed.In our example, just to show you that you don't I<really> have to return anARRAY reference, we'll choose a HASH reference to represent our object.A HASH works out well as a generic record type: the C<{ELEMSIZE}> field willstore the maximum element size allowed, and the C<{ARRAY}> field will hold thetrue ARRAY ref. If someone outside the class tries to dereference theobject returned (doubtless thinking it an ARRAY ref), they'll blow up.This just goes to show you that you should respect an object's privacy. sub TIEARRAY { my $class = shift; my $elemsize = shift; if ( @_ || $elemsize =~ /\D/ ) { croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size"; } return bless { ELEMSIZE => $elemsize, ARRAY => [], }, $class; }=item FETCH this, indexThis method will be triggered every time an individual element the tied arrayis accessed (read). It takes one argument beyond its self reference: theindex whose value we're trying to fetch. sub FETCH { my $self = shift; my $index = shift; return $self->{ARRAY}->[$index]; }If a negative array index is used to read from an array, the indexwill be translated to a positive one internally by calling FETCHSIZEbefore being passed to FETCH.As you may have noticed, the name of the FETCH method (et al.) is the samefor all accesses, even though the constructors differ in names (TIESCALARvs TIEARRAY). While in theory you could have the same class servicingseveral tied types, in practice this becomes cumbersome, and it's easiestto keep them at simply one tie type per class.=item STORE this, index, valueThis 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 atwhich we're trying to store something and the value we're trying to putthere.In our example, C<undef> is really C<$self-E<gt>{ELEMSIZE}> number ofspaces so we have a little more work to do here: 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; }Negative indexes are treated the same as with FETCH.=item FETCHSIZE thisReturns the total number of items in the tied array associated withobject I<this>. (Equivalent to C<scalar(@array)>). For example: sub FETCHSIZE { my $self = shift; return scalar @{$self->{ARRAY}}; }=item STORESIZE this, countSets the total number of items in the tied array associated withobject I<this> to be I<count>. If this makes the array larger thenclass's mapping of C<undef> should be returned for new positions.If the array becomes smaller then entries beyond count should bedeleted. In our example, 'undef' is really an element containingC<$self-E<gt>{ELEMSIZE}> number of spaces. Observe: 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(); } } }=item EXTEND this, countInformative call that array is likely to grow to have I<count> entries.Can be used to optimize allocation. This method need do nothing.In our example, we want to make sure there are no blank (C<undef>)entries, so C<EXTEND> will make use of C<STORESIZE> to fill elementsas needed: sub EXTEND { my $self = shift; my $count = shift; $self->STORESIZE( $count ); }=item EXISTS this, keyVerify that the element at index I<key> exists in the tied array I<this>.In our example, we will determine that if an element consists ofC<$self-E<gt>{ELEMSIZE}> spaces only, it does not exist: sub EXISTS { my $self = shift; my $index = shift; return 0 if ! defined $self->{ARRAY}->[$index] || $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE}; return 1; }=item DELETE this, keyDelete the element at index I<key> from the tied array I<this>.In our example, a deleted item is C<$self->{ELEMSIZE}> spaces:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -