When variables behave differently - Tie in Perl
Archive - Originally posted on "The Horse's Mouth" - 2011-08-28 06:10:05 - Graham EllisDeep in the bowels of any programming language is code to store information into a variable, and get information back from that variable. And in a language that's dynamic in its memory allocation, there will also be code to construct and destroy variables.
Does that sound a bit "object oriented". Intentionally so. And in Perl, you can actually get at the four
Here's a program that appears to overwrite a variable 12 times ...
for ($k=0;$k<13;$k++) {
$hand = $pack[$k];
}
And then appears to go into an infinite loop printing out the last item stored:
while ($thiscard = $hand) {
print "playing card $thiscard\n";
}
It doesn't actually work like that, though, in my example - complete source [here] - because of two extra lines I have added:
use stack;
tie $hand,"stack";
These two lines have replaced the standard behaviour of a scalar for the variable $hand - and in the file stack.pm I have defined a new constructor that sets up a list. In the "setter" I have stored each new value onto the end of that list, and in the "getter" I have removed an item from the end of the list. Thus making the variable $hand into a new way of handling a stack.
By replacing the pop with shift in stack.pm, I could turn the tie class into a queue variable - first in, first out, return flas when the queue is empty. This sort of thing is very clever, but you need to consider whether or not anyone who has to maintain the code late on will understand it.
Tieing can also be used on a scalar to make a variable persist from one run of a program to the next (by the simple means of reading and writing to a text file) - see [here] for the call and [here] for the definition. And tieing can be used for lists and hashes too. With a list, you could treat each line of a file as a member of a list ... with a hash you could use a unique key in a database table to be the hash key - so make your database selects, inserts and updates transparent to your code user.
You'll find a number of examples in the resources for our tieing module which we sometimes teach on custom courses (I covered it on one of last week's Perl courses) and I'll cover it on public Perl for Larger Projects courses - often at an "overview" level but also happy to go into some more detail is it's of specific use to any of the delegates. But if you're thinking of using tieing in a piece of production code - please consider maintainability and efficiency before you commit. Both of these concerns can be answered, but it's best to answer them early on and be aware of what you're doing.