You would want to do a typeglob assignment. If you assign
an anonymous function to a typeglob, you define that
function. Like this:
package Stringify;
sub objectToString {
my $name = shift;
return sub {
$name . (shift)->getParametersAndValues();
};
}
# Time passes
package Fu;
*toString = Stringify::objectToString("Fu");
But I should note that you can make this nicer with
overload and an autogenerated method. For instance:
package Stringify;
use strict;
use Carp;
sub import {
my $pkg = caller();
my $code = qq(
# A trick for custom error reporting - see perlsyn.
\n# line 1 "'Autogenerated for $pkg by Stringify'"
package $pkg;
use overload '""' => sub {
__PACKAGE__ . (shift)->getParametersAndValues();
};
);
eval($code);
if ($@) {
confess("Cannot autogenerate stringification for package '$pkg': $
+@
The code is:\n$code");
}
}
1;
would allow you to simply:
package Fu;
use Stringify; # Use objects as strings, and they stringify
If you want you could create an autogenerated function
called toString and pass a reference to that function to
overload.