Chapter 3
a class can provide. In the last chapter I demonstrated how to provide accessor 
mutators by writing a method for each attribute. When the method has no param 
eters, it returns the value of the attribute; with one parameter, it sets the value of 
the attribute.
It doesn't take long before writing accessor mutator methods gets old. Every 
one is essentially the same. Fortunately, there are a number of better ways to 
choose from!
Auto Rolling Your Own
The basic problem is simple you have a number of subroutines to generate, and 
they all do the same thing on different data. Fortunately, Perl is a highly dynamic 
language, and it's easy to generate new subroutines at runtime. Here's an example 
that creates a simple accessor mutator for a set of attributes stored in the package 
variable @ATTRIBUTES:
package BOA::Logger;
# initialize array of attribute names
@ATTRIBUTES = qw(filename level format);
# create a subroutine for each attribute
foreach my $attribute (@ATTRIBUTES) {
   *$attribute = sub {
       my $self = shift;
       $self >{$attribute} = shift if @_;
       return $self >{$attribute};
    }
}
This block of code works by assigning a closure to a symbol table entry with the 
same name as the attribute. After this code runs, there will be three new methods 
available in the BOA::Logger package filename(), level(), and format(). If you 
needed to add a new attribute to the package, it would be a simple matter of 
adding it to @ATTRIBUTES.
Another way to accomplish the same effect is to use AUTOLOAD(). When you call 
a method on an object that doesn't exist in the object's class or any parent classes, 
Perl looks to see if the class has a method in it called AUTOLOAD(). If not, Perl will 
traverse the inheritance hierarchy the same way it does when looking for normal 
methods. When Perl finds a suitable AUTOLOAD() method, the package global 
$AUTOLOAD is set to the full name of the method being called, and AUTOLOAD() is called.
86






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