Perl Module Basics
sub level {
my ($self, $level) = @_;
if (@_ == 2) {
croak("Argument to level() must be a non negative integer!")
unless $level =~ /^\d+$/;
$self >{level} = $level;
}
return $self >{level};
}
It might seem convenient to allow users to simply access the hash keys directly:
$logger >{level} = 100; # works, but not a good idea
The problem with this is that it breaks the encapsulation of your class. You are no
longer free to change the implementation of BOA::Logger you can't change the
class to use an array underneath or change the keys of the hash. Also, you can't per
form any checking of the value set for an attribute. As a general rule, all access to
an object oriented class should be through methods, either class methods or
object methods.
Destructors
The non OO version of BOA::Logger had a useful feature that this version lacks
it prints a message when the program exits. You can provide this by setting up a
destructor for the class. Destructors are the opposite of constructors they are
called when an object is no longer being used.
14
They can perform cleanup actions,
such as closing file handles. To create a destructor, simply define a method called
DESTROY.
sub DESTROY {
my $self = shift;
$self >write($self >{level}, "BOA log exited: " . localtime(time) . "\n");
$self >{fh} >close() or die "Unable to close log file : $!";
}
Class Data
By now you know that BOA is a big ol' application. As such, there are many modules
that will want to write to the same log file. With the example OO implementation,
14. When the last variable holding a reference to the object goes out of scope, or at program
exit whichever comes first
43
43
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