X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2Fcurry.pm;fp=lib%2Fcurry.pm;h=5cbaee496c3eced5208eb76c4d1ecdce43587609;hb=b1b9749593dbf3c98768076d9495bc82714b0d3b;hp=58bbeb4d04de045c7b683f52c28f9e1069ac80dc;hpb=e2439657cecc7f65ae987c229f183f6f4693a7af;p=p5sagit%2Fcurry.git diff --git a/lib/curry.pm b/lib/curry.pm index 58bbeb4..5cbaee4 100644 --- a/lib/curry.pm +++ b/lib/curry.pm @@ -3,6 +3,12 @@ package curry; our $VERSION = '1.000000'; $VERSION = eval $VERSION; +our $curry = sub { + my ($invocant, $code) = splice @_, 0, 2; + my @args = @_; + sub { $invocant->$code(@args => @_) } +}; + sub AUTOLOAD { my $invocant = shift; my ($method) = our $AUTOLOAD =~ /^curry::(.+)$/; @@ -16,6 +22,16 @@ package curry::weak; use Scalar::Util (); +$curry::weak = sub { + my ($invocant, $code) = splice @_, 0, 2; + Scalar::Util::weaken($invocant) if Scalar::Util::blessed($invocant); + my @args = @_; + sub { + return unless $invocant; + $invocant->$code(@args => @_) + } +}; + sub AUTOLOAD { my $invocant = shift; Scalar::Util::weaken($invocant) if Scalar::Util::blessed($invocant); @@ -59,6 +75,46 @@ is equivalent to: }; }; +If you want to pass a weakened copy of an object to a coderef, use the +C< $weak > package variable: + + use curry::weak; + + my $code = $self->$curry::weak(sub { + my ($self, @args) = @_; + print "$self must still be alive, because we were called (with @args)\n"; + }, 'xyz'); + +which is much the same as: + + my $code = do { + my $sub = sub { + my ($self, @args) = @_; + print "$self must still be alive, because we were called (with @args)\n"; + }; + Scalar::Util::weaken(my $weak_obj = $self); + sub { + return unless $weak_obj; # in case it already went away + $sub->($weak_obj, 'xyz', @_); + } + }; + +There's an equivalent - but somewhat less useful - C< $curry > package variable: + + use curry; + + my $code = $self->$curry::curry(sub { + my ($self, $var) = @_; + print "The stashed value from our ->something method call was $var\n"; + }, $self->something('complicated')); + +Both of these methods can also be used if your scalar is a method name, rather +than a coderef. + + use curry; + + my $code = $self->$curry::curry($methodname, $self->something('complicated')); + =head1 RATIONALE How many times have you written