Suppose you wanted to do something like this to a family of related objects. How would you assign the anonymous function to be a method of each class? (I can do that trick in JavaScript using ObjectName.prototpye.methodName, but how would I do that in Perl?)
For example, what I would like to do is:
...
sub ObjectToString {
my $name = shift;
return sub {
my $s = $name . $self->getParametersAndValues();
return $s;
}
}
...
package Fu;
sub toString = ObjectToString("Fu");
...
package Bar;
sub toString = ObjectToString("Bar");
...
package Baz;
sub toString = ObjectToString("Baz");
...
Then I would use it like this:
my ($foo, $bar, $baz);
$foo = Fu->new();
# do stuff with foo...
print $foo->toString();
$bar = Bar->new();
# do stuff with bar...
print $bar->toString();
...
The obvious answer here is to use Inheritance™, but what if, for some reason, I don't want to use inheritance? Can I still accomplish what I want to? |