Perl Module Basics
Tying Scalars
Sometimes a class is so simple that its entire interface can be represented by a tied 
scalar. For example, imagine that the BOA::Thermostat module implements an 
interface to a thermometer and a heater for the BOA spacecraft. If this class pro 
vided a tied scalar interface, then reads could correspond to checking the current 
temperature and writes could correspond to opening or closing the heating vents. 
Here's some example code that keeps compartment 10 of the spacecraft between 
20 and 30 degrees:
use BOA::Thermostat;
# tie $thermo to temperator controls for compartment 10, the captain s quarters
tie $thermo,  BOA::Thermostat , compartment => 10;
# enter infinite loop
while (1) {
   # check temperature
   if ($thermo <= 20) {      # too cool?
      $thermo = 1;           # open the vents
   } elsif ($thermo >= 30) { # too hot?
      $thermo = 0;           # close the vents
   }
   sleep(30);                # pause for 30 seconds
}
The code starts by using the BOA::Thermostat module. Next, a call to the tie function 
is made. This call tells Perl that the $thermo variable's implementation will be pro 
vided by the BOA::Thermostat class. Whenever the program accesses the $thermo
variable, a method in the BOA::Thermostat class is called. The call also passes the 
compartment number to the BOA::Thermostat class using a named parameter 
style. The program then enters an infinite loop, checking the temperature and 
opening or closing the vents as appropriate.
This example highlights a key difference between tying and overloading the 
ability to handle assignment. An overloaded class could not provide this interface 
because after the first assignment the $thermo variable would no longer contain a 
reference to an overloaded object. Tied variables provide magic containers, whereas 
overloaded objects provide magic values that can be assigned to variables. The 
difference is subtle but important to understand.
57
57






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