|
perltie - how to hide an object class in a simple variable
tie VARIABLE, CLASSNAME, LIST
$object = tied VARIABLE
untie VARIABLE
Prior 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 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.
Now you can.
The tie() 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 ALL CAPS,
which is a convention that Perl uses to indicate that they're called
implicitly rather than explicitly--just like the BEGIN() and END()
functions.
In the tie() call, VARIABLE is the name of the variable to be
enchanted. CLASSNAME is the name of a class implementing objects of
the correct type. Any additional arguments in the LIST are passed to
the appropriate constructor method for that class--meaning TIESCALAR(),
TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments
such as might be passed to the dbminit() function of C.) The object
returned by the "new" method is also returned by the tie() function,
which would be useful if you wanted to access other methods in
CLASSNAME. (You don't actually have to return a reference to a right
"type" (e.g., HASH or CLASSNAME) so long as it's a properly blessed
object.) You can also retrieve a reference to the underlying object
using the tied() function.
Unlike dbmopen(), the tie() function will not use or require a module
for you--you need to do that explicitly yourself.
A 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 for
scalars 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 current
system priority is retrieved and returned. If those variables are set,
then the process's priority is changed!
We'll use Jarkko Hietaniemi <jhi@iki.fi>'s BSD::Resource class (not
included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
from your system, as well as the getpriority() and setpriority() system
calls. Here's the preamble of the class.
package Nice;
use Carp;
use BSD::Resource;
use strict;
$Nice::DEBUG = 0 unless defined $Nice::DEBUG;
- 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:
-
sub TIESCALAR {
my $class = shift;
my $pid = shift || $$;
-
if ($pid !~ /^\d+$/) {
carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
return undef;
}
-
unless (kill 0, $pid) {
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 an
exception if its constructor should fail. While this is how dbmopen() works,
other classes may well not wish to be so forgiving. It checks the global
variable $^W to see whether to emit a bit of noise anyway.
- 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 SCALAR 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 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 renice
fails--there's no place for us to return an error otherwise, and it's
probably the right thing to do.
- 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. Don't worry about
returning a value from STORE -- the semantic of assignment returning the
assigned value is implemented with FETCH.
-
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: $!";
}
}
- UNTIE this
-
This method will be triggered when the untie occurs. This can be useful
if the class needs to know when no further calls will be made. (Except DESTROY
of course.) See The untie Gotcha below for more details.
- 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 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;
}
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
TIESCALAR classes are certainly possible.
A class implementing a tied ordinary array should define the following
methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY.
FETCHSIZE and STORESIZE are used to provide $#array and
equivalent scalar(@array) access.
The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are
required if the perl operator with the corresponding (but lowercase) name
is to operate on the tied array. The Tie::Array 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 DELETE and EXISTS in
Tie::Array simply croak.
In addition EXTEND will be called when perl would have pre-extended
allocation in a real array.
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:
use FixedElem_Array;
tie @array, 'FixedElem_Array', 3;
$array[0] = 'cat';
$array[1] = 'dogs';
The preamble code for the class is as follows:
package FixedElem_Array;
use Carp;
use strict;
- 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 ARRAY ref) will be accessed.
-
In our example, just to show you that you don't really have to return an
ARRAY reference, we'll choose a HASH reference to represent our object.
A HASH works out well as a generic record type: the {ELEMSIZE} field will
store the maximum element size allowed, and the {ARRAY} field will hold the
true ARRAY ref. If someone outside the class tries to dereference the
object 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;
}
- 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.
-
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 index
will be translated to a positive one internally by calling FETCHSIZE
before being passed to FETCH. You may disable this feature by
assigning a true value to the variable $NEGATIVE_INDICES in the
tied array class.
-
As you may have noticed, the name of the FETCH method (et al.) is the same
for all accesses, even though the constructors differ in names (TIESCALAR
vs TIEARRAY). 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.
- 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.
-
In our example, undef is really $self->{ELEMSIZE} number of
spaces 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}";
}
$self->EXTEND( $index ) if $index > $self->FETCHSIZE();
$self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
}
-
Negative indexes are treated the same as with FETCH.
- FETCHSIZE this
-
Returns the total number of items in the tied array associated with
object this. (Equivalent to scalar(@array)). For example:
-
sub FETCHSIZE {
my $self = shift;
return scalar @{$self->{ARRAY}};
}
- STORESIZE this, count
-
Sets the total number of items in the tied array associated with
object this to be count. If this makes the array larger then
class's mapping of undef should be returned for new positions.
If the array becomes smaller then entries beyond count should be
deleted.
-
In our example, 'undef' is really an element containing
$self->{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();
}
}
}
- EXTEND this, count
-
Informative call that array is likely to grow to have 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 (undef)
entries, so EXTEND will make use of STORESIZE to fill elements
as needed:
-
sub EXTEND {
my $self = shift;
my $count = shift;
$self->STORESIZE( $count );
}
- EXISTS this, key
-
Verify that the element at index key exists in the tied array this.
-
In our example, we will determine that if an element consists of
$self->{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;
}
- DELETE this, key
-
Delete the element at index key from the tied array this.
-
In our example, a deleted item is $self->{ELEMSIZE} spaces:
-
sub DELETE {
my $self = shift;
my $index = shift;
return $self->STORE( $index, '' );
}
- CLEAR this
-
Clear (remove, delete, ...) all values from the tied array associated with
object this. For example:
-
sub CLEAR {
my $self = shift;
return $self->{ARRAY} = [];
}
- PUSH this, LIST
-
Append elements of LIST to the array. For example:
-
sub PUSH {
my $self = shift;
my @list = @_;
my $last = $self->FETCHSIZE();
$self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
return $self->FETCHSIZE();
}
- POP this
-
Remove last element of the array and return it. For example:
-
sub POP {
my $self = shift;
return pop @{$self->{ARRAY}};
}
- SHIFT this
-
Remove the first element of the array (shifting other elements down)
and return it. For example:
-
sub SHIFT {
my $self = shift;
return shift @{$self->{ARRAY}};
}
- UNSHIFT this, LIST
-
Insert LIST elements at the beginning of the array, moving existing elements
up to make room. For example:
-
sub UNSHIFT {
my $self = shift;
my @list = @_;
my $size = scalar( @list );
@{$self->{ARRAY}}[ $size .. $#{$self->{ARRAY}} + $size ]
= @{$self->{ARRAY}};
$self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
}
- SPLICE this, offset, length, LIST
-
Perform the equivalent of splice on the array.
-
offset is optional and defaults to zero, negative values count ba |