Using Tied Hashes

What are tied hashes? How do they fit into all of this? You are familiar with a regular hash-an array that uses not just a number as an index, but instead any sort of string (and typically a non-numeric one). When a variable is tied in Perl, all methods that access that variable can be changed. If you have tied a scalar variable named $counter, for example, you can change the behavior of that scalar variable so that it increments each time it is accessed. The following code:

print "$counter\n"; print "$counter\n"; print "$counter\n";

actually prints:

1 2 3

This is because the variable is tied. With a scalar, there are only a few ways to access it. You can FETCH data from it, you can STORE information into it, or you can DESTROY it. Things are a bit more complex with a hash, which is good because it gives us even more power to do what we need to do.

Besides FETCH, STORE, and DESTROY, tied hashes also have DELETE to delete a value in the hash, CLEAR to clear the entire hash, EXISTS to see if a key exists, FIRSTKEY to get the first key in the hash, and NEXTKEY to fetch the next key.

We'll be tying a hash to a database. This allows us to change how the hash behaves and causes it to manipulate a database, simply by modifying values in the hash!

At the moment, this is probably all pretty confusing. Since true learning happens by doing, not just reading, we'll create an example program that ties a hash to a database so that we can track user preferences.



Perl Database Programming
Perl Database Programming
ISBN: 0764549561
EAN: 2147483647
Year: 2001
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net