Commit | Line | Data |
9e15d0fb |
1 | package Object::Tap; |
2 | |
3 | use strict; |
4 | use warnings; |
5 | use base qw(Exporter); |
6 | |
1ab69302 |
7 | our $VERSION = '1.000006'; |
9e15d0fb |
8 | |
9 | our @EXPORT = qw($_tap); |
10 | |
9d1b22e3 |
11 | our $_tap = sub { |
12 | my ($obj, $call, @args) = @_; |
13 | $obj->$call(@args) for $obj; |
14 | $obj |
15 | }; |
9e15d0fb |
16 | |
17 | 1; |
18 | |
19 | =head1 NAME |
20 | |
21 | Object::Tap - Tap into a series of method calls to alter an object |
22 | |
23 | =head1 SYNOPSIS |
24 | |
25 | Instead of writing - |
26 | |
27 | my $thing = My::Class->new(...); |
28 | |
29 | $thing->set_foo(1); |
30 | |
31 | you can instead write - |
32 | |
33 | use Object::Tap; |
34 | |
35 | my $thing = My::Class->new(...)->$_tap(sub { $_[0]->set_foo(1) }); |
36 | |
9d1b22e3 |
37 | We also alias $_ to $_[0] within the subroutine so: |
38 | |
39 | my $thing = My::Class->new(...)->$_tap(sub { $_->set_foo(1) }); |
40 | |
41 | also works. |
42 | |
9e15d0fb |
43 | To realise why this might be useful, consider instead - |
44 | |
45 | My::App->new(...)->$_tap(...)->run; |
46 | |
47 | where a variable is thereby not required at all. |
48 | |
49 | You can also pass extra args - |
50 | |
51 | $obj->$_tap(sub { warn "Got arg: $_[1]" }, 'arg'); |
52 | |
f72e0060 |
53 | or use a method name instead of a sub ref - |
9e15d0fb |
54 | |
55 | my $thing = My::Class->new(...)->$_tap(set_foo => 1); |
56 | |
96021ef6 |
57 | For a 'real' example of how that might be used, one could create and |
58 | initialize an L<HTML::TableExtract> object in one go using - |
59 | |
60 | my $te = HTML::TableExtract->new->$_tap(parse => $html); |
61 | |
9e15d0fb |
62 | =head1 AUTHOR |
63 | |
64 | mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk> |
65 | |
66 | =head1 CONTRIBUTORS |
67 | |
68 | None yet. Well volunteered? :) |
69 | |
70 | =head1 COPYRIGHT |
71 | |
72 | Copyright (c) 2014 the Object::Tap L</AUTHOR> and L</CONTRIBUTORS> |
73 | as listed above. |
74 | |
75 | =head1 LICENSE |
76 | |
77 | This library is free software and may be distributed under the same terms |
78 | as perl itself. |
79 | |
80 | =cut |