Chapter 2
Here's an example of using the module, which would be placed in a separate
script file:
use BOA::Logger;
my $logger = BOA::Logger >new( logs/boa.log );
$logger >level(10);
$logger >write(10, "Hello world!");
One thing to notice is that making the module object oriented allows you to sim
plify the names of the subroutines in BOA::Logger. This is because object oriented
modules should never export their methods. Thus there's no need to worry about
confusion with other subroutines called level() and write(). Another advantage
of the object oriented BOA::Logger is that you can have multiple loggers active at
the same time with different log files and different log levels.
Accessors and Mutators
The level() method shown earlier is called a mutator it is used to change, or
mutate, the value of the level attribute. It is not an accessor since it doesn't allow
the user to query the current value of the level attribute. An accessor for the value
of level could potentially be useful a user of the module could avoid executing
costly debugging code if the log level is set too low to show the results. Here's a new
level() method that functions as both an accessor and a mutator:
sub level {
my ($self, $level) = @_;
$self >{level} = $level if @_ == 2;
return $self >{level};
}
Now it's possible to call the level() method with no arguments to receive the current
value of the level attribute. For example, this checks the log level before calling write():
if ($logger >level() >= 5) {
$logger >write(5, "Here s the full state of the system: " . dump_state());
}
This way you can avoid calling dump_state() if the result will never be printed.
Writing accessor mutators for each attribute in your object enables you to
perform checks on the value being set. For example, it might be useful to verify
that the level value is a nonnegative integer. One way to do this is to check it with a
regular expression that only matches digits:
42
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