Re: RFC from a newbie: Method References

2000-12-16 Thread Michael G Schwern

On Fri, Dec 15, 2000 at 11:23:23PM -0800, Ian Hickson wrote:
 Having said that: The only feature that I really miss from Perl 5 is the
 lack of method pointers -- that is, references to functions in a package
 with an associated object.

Oh, that's easy.  Use a closure...

my $foo = Foo-new;
my $meth_ref = sub { $foo-method };
$methodref();

In fact, here's an example implementation...

package Class::MethRef;
use strict;

sub meth_ref {
my($proto, $method, @args) = @_;
return sub { $proto-$method(@args) };
}


So this...

my $meth_ref = $obj-meth_ref('foo', @some_stuff);
$meth_ref-();

is equivalent to this..

$obj-foo(@some_stuff);

You could even make the meth_ref take additional (or overriding) arguments.

Its a good idea, I'll put Class::MethRef on CPAN soon.


-- 
Michael G. Schwern   [EMAIL PROTECTED]http://www.pobox.com/~schwern/



Re: RFC from a newbie: Method References

2000-12-16 Thread Jeremy Howard

Michael G Schwern wrote:
 package Class::MethRef;
 use strict;

 sub meth_ref {
 my($proto, $method, @args) = @_;
 return sub { $proto-$method(@args) };
 }


 So this...

 my $meth_ref = $obj-meth_ref('foo', @some_stuff);
 $meth_ref-();

 is equivalent to this..

 $obj-foo(@some_stuff);

 You could even make the meth_ref take additional (or overriding)
arguments.

 Its a good idea, I'll put Class::MethRef on CPAN soon.

Something to be careful of--it's easy to create a circular reference when
using method pointers. As a result, neither the referrer nor referee objects
are ever destroyed.

When using method references it's important that your class keeps track of
its references, and explicitly removes them when done to allow object
destruction to occur. Perhaps this could be incorporated into
Class::MethRef?