x
Loading
 Loading
Hello, Guest | Login | Register

Fit to be Tied, Part Two

Want to tie a complex data type? Here’s how, courtesy of Perl guru Randal Schwartz.

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:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace