don't try and call a method on a weakened object that already disappeared
[p5sagit/curry.git] / lib / curry.pm
1 package curry;
2
3 our $VERSION = '1.0';
4 $VERSION = eval $VERSION;
5
6 sub AUTOLOAD {
7   my $invocant = shift;
8   my ($method) = our $AUTOLOAD =~ /^curry::(.+)$/;
9   my @args = @_;
10   return sub {
11     $invocant->$method(@args => @_);
12   }
13 }
14
15 package curry::weak;
16
17 use Scalar::Util ();
18
19 sub AUTOLOAD {
20   my $invocant = shift;
21   Scalar::Util::weaken($invocant) if Scalar::Util::blessed($invocant);
22   my ($method) = our $AUTOLOAD =~ /^curry::(.+)$/;
23   my @args = @_;
24   return sub {
25     return unless $invocant;
26     $invocant->$method(@args => @_);
27   }
28 }
29
30 1;
31
32 =head1 NAME
33
34 curry - Create automatic curried method call closures for any class or object
35
36 =head1 SYNOPSIS
37
38   use curry;
39
40   my $code = $obj->curry::frobnicate('foo');
41
42 is equivalent to:
43
44   my $code = sub { $obj->frobnicate(foo => @_) };
45
46 Additionally,
47
48   use curry::weak;
49
50   my $code = $obj->curry::weak::frobnicate('foo');
51
52 is equivalent to:
53
54   my $code = do {
55     Scalar::Util::weaken(my $weak_obj = $obj);
56     sub {
57       return unless $weak_obj; # in case it already went away
58       $weak_obj->frobnicate(foo => @_)
59     };
60   };
61
62 =head1 RATIONALE
63
64 How many times have you written
65
66   sub { $obj->something($some, $args, @_) }
67
68 or worse still needed to weaken it and had to check and re-check your code
69 to be sure you weren't closing over things the wrong way?
70
71 Right. That's why I wrote this.
72
73 =head1 AUTHOR
74
75 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
76
77 =head1 CONTRIBUTORS
78
79 None yet - maybe this software is perfect! (ahahahahahahahahaha)
80
81 =head1 COPYRIGHT
82
83 Copyright (c) 2012 the Import::Into L</AUTHOR> and L</CONTRIBUTORS>
84 as listed above.
85
86 =head1 LICENSE
87
88 This library is free software and may be distributed under the same terms
89 as perl itself.