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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|