Last month, I introduced the tie operator, illustrating how tie can be used with a scalar variable to give additional behaviors to getting and setting the value of the variable. This time, let’s continue and look at other data types that can be tied.
Another common Perl data structure to tie is a hash. This code…
tie %h, MyTie, @list;
… translates to:
MyTie->TIEHASH(@list);
Again, the constructor is expected to return an object, which becomes the secret object of the tied variable. And, as before, you can call tied to get at that object.
The FETCH() method now receives a parameter, because it needs to know which key to fetch. That means…
$x = $h{SomeKey};
… turns into:
$x = tied(%h)->FETCH("SomeKey");
Storing a value now gets an additional parameter as well. The two parameters are the key and the new value. So, the code…
$h{SomeKey} = "newvalue";
… turns into:
tied(%h)->STORE("SomeKey", "newvalue");
It’s possible to use the same class for tying both scalars and hashes, but you’ll have to keep track of whether you were called with TIESCALAR or TIEHASH to know what kind of FETCH() and STORE() to do. That can get messy, so another strategy is to use your public class as a dispatch to the proper private implementation class:
package MyTie; sub TIESCALAR { my $class = shift; $class->scalar_class->TIESCALAR(@_); } sub scalar_class { “MyTie::Scalar” } sub TIEHASH { my $class = shift; $class->hash_class->TIEHASH(@_); } sub hash_class { “MyTie::Hash” } package MyTie::Scalar; # normal tied scalar stuff here package MyTie::Hash; # normal…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: