14.1. Making and Using a DBM File14.1.2. SolutionUse tie to open the database and make it accessible through a hash. Then use the hash as you normally would. When you're done, call untie:
14.1.3. DiscussionAccessing a database as a hash is powerful but easy, giving you a persistent hash that sticks around after the program using it has finished running. It's also much faster than loading in a new hash every time; even if the hash has a million entries, your program starts up virtually instantaneously. The program in Example 14-1 treats the database as though it were a normal hash. You can even call keys or each on it. Likewise, exists and defined are implemented for tied DBM hashes. Unlike a normal hash, a DBM hash does not distinguish between those two functions. Example 14-1. userstats
We use who to get a list of users logged in. This typically produces output like: gnat ttyp1 May 29 15:39 (coprolith.frii.com) If the userstats program is called without any arguments, it checks who's logged on and updates the database appropriately. If the program is called with arguments, these are treated as usernames whose information will be presented. The special argument "ALL" sets @ARGV to a sorted list of DBM keys. For large hashes with many keys, this is prohibitively expensive—a better solution would be to use the BTREE bindings of DB_File described in Recipe 14.5. The old dbmopen function still works. Here's the solution rewritten to use dbmopen and dbmclose:
14.1.4. See AlsoThe documentation for the standard modules GDBM_File, NDBM_File, SDBM_File, and DB_File, some of which are in Chapter 32 of Programming Perl; perltie(1); Chapter 14 of Programming Perl; the discussion on the effect of your umask on file creation in Recipe 7.1; Recipe 13.15
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|