Module Design and Implementation
Here's an example of creating accessor mutators on demand using AUTOLOAD():
package BOA::Logger;
use Carp;
# initialize hash of attribute names
%ATTRIBUTES = map { $_ => 1 } qw(filename level format);
sub AUTOLOAD {
return if $AUTOLOAD =~ /DESTROY$/; # skip calls to DESTROY()
my ($name) = $AUTOLOAD =~ /([^:]+)$/; # extract method name
# check that this is a valid accessor call
croak("Unknown method $AUTOLOAD called ") unless $ATTRIBUTES{$name};
# create the accessor mutator and install it as &$name
*$name = sub {
my $self = shift;
$self >{$name} = shift if @_;
return $self >{$name};
};
goto &$name; # jump to the new method with the magic goto(&) call
}
This code is more complicated than just creating all the accessors upfront, but if
you have many attributes that are rarely called, it might be more efficient. Notice
that AUTOLOAD() will only be called on the first call to each accessor; after that the
newly created subroutine is installed and will be called directly. You might be
tempted to skip this step and simply do the access directly in the AUTOLOAD() method,
but this will slow your module significantly since Perl will spend time checking for
the missing method every time the accessor is called.
Either of the preceding options is a clean way of auto generating methods.
8
However, they require you to do some unnecessary work, which no doubt offends
your instincts as a Perl programmer. It's unnecessary because there are two excellent
modules Class::Struct and Class::MethodMaker that use similar techniques
but provide a much more convenient interface. As a bonus, they also handle
writing those repetitive constructors too!
8. And efficient too all the generated closures share the same compiled code.
87
87
footer
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