Main Content

Changing a variable behaviour in Perl - tieing

Archive - Originally posted on "The Horse's Mouth" - 2009-06-16 07:41:58 - Graham Ellis

What can you do with a scalar variable? When you reduce it to lowest level programming principles, not a lot ... you can create it, destroy it, save a value into it, and read a value back from it. That's about it, when you think of it!

In Perl, the low level memory accessors within the language go through just a handful of routines (it's really an object interface), which you can override for individual variables if you like. What does this mean? It means you can change the characteristics of a variable if you like. Look at this program:

use propercase;
tie $yourname,"propercase";
print "Enter your name ";
$yourname = <STDIN>;
print "Welcome, $yourname";


Good - but because of my propercase class it will force the name to be properly cased:

earth-wind-and-fire:~/jun09 grahamellis$ perl ppc
Enter your name graHam
Welcome, Graham
earth-wind-and-fire:~/jun09 grahamellis$


Clever, isn't it? ... Here is the module that defines "propercase"

package propercase;
sub TIESCALAR {
  my ($class,$value) = @_;
  bless $value,$class; }
sub STORE {
  my ($inst,$value) = @_;
  $$inst = ucfirst(lc($value)); }
sub FETCH {
  my ($inst) = @_;
  return $$inst; }
1;


Other examples of a tied scalar are for a variable which automatically has spaces trimmed off the start and end, a stack (where each time to save a value it is actually pushed onto a list, and each time you call it back, the next value is returned) and a variable that persists between runs of your program, as tieing links tha variable to a file on the disc.

Tieing is also possible to lists and hashes - in the case of a hash it can provide a very useful interface indeed to a database table - you can insert / replace / select / update database records with simple assignment statements. The methods you need to implement to use a tied hash are TIEHASH (the constructor), STORE, FETCH, EXISTS, DELETE, CLEAR, FIRSTKEY and NEXTKEY. There are examples in our Tieing in Perl resource module, which is covered on our Perl for Larger Projects course.


Illustration - delegates on a Perl course at Well House Manor