ACCC Home Page ACADEMIC COMPUTING and COMMUNICATIONS CENTER
Accounts / Passwords Email Labs / Classrooms Telecom Software Computing and Network Services Education / Teaching Getting Help
 
Seminar - Perl II
0. Contents 1. Intro 2. Sources 3. References 4. Packages 5. Classes
6. Ties & DBM 7. Typeglobs 8. CGI 9. Security 10. Example  

Ties and DBM

   
 
     
Ties
 

A tie is a way for perl to associate a variable with a set of functions. For example, if you tie a scalar to a set of functions, you will implicitly call a function every time you read or write that scalar.

For example, suppose you have your computer hooked up to a thermometer and thermostat. When you read your variable, you want to read the thermometer, and when you set it, you want to set the thermostat. Once the tie is made, you can:

  print $temp;   # prints current temperature
  sleep (100);
  print $temp;   # prints temperature again
                 # might be different
  $temp = 75;    # set thermostat
  print $temp;   # prints temperature
                 # might not be 75 yet

A tie can also be used for debugging. If you need to trace activity of a variable, just tie it to functions that log reads and writes.

 
     
DBM
 

Ties are really an extension of ways to use DBM libraries in a perlish fashion. Berkeley DB and other DBM libraries are usually written in C, and are used to create associative arrays on disk. This makes the hash persistent, as well as potentially larger than available memory.

The really easy way to use DBM libraries is to use tie to connect a disk file with a perl hash. After that, just use the hash in the normal perl fashion. The dbm file on disk will always reflect the hash, and will survive when the program exits. You can use the data next time.

One caveat. The keys and values must be strings. They cannot be references. You can, indeed, assign a reference as a key or value, but perl will stringify that reference before writing to the disk file. That means you won't be able to recover info if you write out references, even though no error will be thrown. There are libraries that help with this, by converting references to a string of the actual data referenced.

 use DB_File;
 use Fcntl;

 tie %h, "DB_File", "file.dat", O_RDWR|O_CREAT, 0600, $DB_HASH;
    ## Use %h normally.  Results are reflected in file.dat
       ...
 untie %h;

The above example uses DB_File, or Berkeley DB. This is quite versatile, although perl doesn't let you get at all of the options. You can use this for hashes, arrays, and there is even a way to preserve insert order for hashes.

Other DBM libraries are available, too. Be aware that they are not disk-compatible. You can use multiple DBM libraries simultaneously if you need to convert from one format to another.

 
 

Perl II Previous: 5. Classes Next: 7. Typeglobs


1999-3-3  BobG
UIC Home Page Search UIC Pages Contact UIC