http://www.perlmonks.org?node_id=109280


in reply to Generating similar functions in unrelated objects
in thread Why I hate File::Find and how I (hope I) fixed it

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.