Main Content

Making variables persistant, pretending a database is a variable and other Perl tricks

Archive - Originally posted on "The Horse's Mouth" - 2009-08-27 07:06:52 - Graham Ellis

Have a look at this Perl program:

use fyle;
tie $counter,"fyle";
 
$counter = $counter + 1;
print ("This is access no. $counter\n");


Apart from the rather curious module loaded at the top, this seems to take an undefined variable, set it to one, and print it out. What a - err - pointless (!) program. But:

Dorothy-2:pl grahamellis$ perl bowtie
This is access no. 11
Dorothy-2:pl grahamellis$ perl bowtie
This is access no. 12
Dorothy-2:pl grahamellis$ perl bowtie
This is access no. 13
Dorothy-2:pl grahamellis$ perl bowtie
This is access no. 14
Dorothy-2:pl grahamellis$


What is happening?

Deep within Perl, there are a very limited number of operations that can be performed with a scalar - it can be created and destroyed, it can be read and written ... and that's about it. And these operations can be redefined by a class, and then applied to individual variables via a tie command ... which is what I have done here.

So in my example, the variable is persistent. Inside the class, it's actually stored in a data file that is read each time the variable is read, and overwritten each time a new values is saved to the variable. So it lasts from one run of the program to the next.

The source code shown above is also available here, and the definition of tieing a variable to a filecontents is here.

You can do a lot more with tieing. We have an example of connecting to a flat file database (NDBM) here (that calls up a standard tie class shipped with Perl). There's an example that forces strings in a variable to always be treated as lower case here and here. Finallly, a tie class which maps a file to a hash here.




Another new example / Perl trick ... see here for a short example / explanation of binary data handling in Perl