Chapter 2
Tying Hashes
By far the most commonly used tied interface is the tied hash. Hashes are so inher 
ently flexible that they lend themselves well to representing an interface to a variety of 
data types. In fact, Perl's support for tied variables evolved from support for tying 
hashes to database files using dbmopen() into the general mechanism it is today.
One common use for tied hashes is to provide lazy computation and caching 
for some large dataset. For example, BOA::Network::DNS provides a tied hash 
interface for network name to IP mappings. Here's an example using the module:
use BOA::Network::DNS;
# tie hash to BOA::Network::DNS   provide nameserver as argument to constructor
tie %dns,  BOA::Network::DNS , nameserver =>  10.0.0.1 ;
# lookup IP address for www.perl.com
print "www.perl.com : ", $dns{ www.perl.com } || "not found!", "\n";
# do a reverse lookup for the DNS server
print "The name for the DNS server is: ", $dns{ 10.0.0.1 } || "not found!", "\n";
Obviously it would be impossible to prepopulate a hash with all the possible 
names and addresses on the Internet, but a tied hash allows you to pretend that 
you have. Also, as you'll see, the hash can very easily hold onto the results of past 
lookups to improve performance.
To implement a tied hash interface, you must provide eight methods 
TIEHASH(), FETCH(), STORE(), DELETE(), EXISTS(), CLEAR(), FIRSTKEY(), and NEXTKEY().
Here's TIEHASH() the constructor:
package BOA::Network::DNS;
sub TIEHASH {
   my $pkg = shift;
   my $self = { @_ }; # retrieve named options into $self hash ref
   # check for required  nameserver  option
   croak("Missing nameserver address!") unless exists $self >{nameserver};
   # initialize cache to an empty hash
   $self >{cache} = {};
   # bless $self and return
   return bless($self, $pkg);
}
60






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

web hosting perl

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved