Q&A
Q1: | Can I put functions in my class, and call them directly without an object? |
A1:
| Yes. In object-oriented terminology these are called class methods. To call a subroutine named doit (and retrieve its value) in a class named Widget you can do any of the following:
$value = Widget->doit();
$value = Widget::doit();
$value = doit Car;
The last one may look odd, but it's a piece of syntax sugar that means the same thing as the others. | Q2: | This hour missed a lot of object-oriented stuff. There was no inheritance! No polymorphism! |
A2:
| There's far, far too much to cover in an hour. Perl includes these manual pages dedicated to objects: perlboot, perltoot, perltootc, perlobj, and perlbot. For an entire book on Perl objects, I'd recommend Object Oriented Perl by Damian Conway. | Q3: | If my object has lots and lots of properties, how can I access them if I don't want to create a function for each one of them? | Q4: | If you call a method on an object, and that method doesn't exist in the class, Perl looks for a subroutine named AUTOLOAD and calls that instead. The first argument will be the object, the remaining arguments will be passed as well, and a special variable called $AUTOLOAD will be set to the class::method name you were trying to access. Here's a simple autoloader that could be used to implement a new method called filename in your TYPFileInfoOO class. |
our($AUTOLOAD); # This goes near the top of the class
sub AUTOLOAD { # This can go anywhere
my($self, $value)=@_;
my($property)=($AUTOLOAD=~m/::(.*?)$/);
die "No property $property" unless exists $self->{$property};
if (defined $value) {
return $self->{$property}=$value;
} else {
return $self->{$property}
}
}
If a property does not exist inside of $self, the AUTOLOAD subroutine dies. If it does, the property value is changed to $value if $value is defined; otherwise it's returned.
If you add more key/value pairs to the hash, this AUTOLOAD will give you access to them as properties.
|