1Sub::Exporter::TutorialU(s3e)r Contributed Perl DocumentaStuibo:n:Exporter::Tutorial(3)
2
3
4
6 Sub::Exporter::Tutorial - a friendly guide to exporting with
7 Sub::Exporter
8
10 $Id: /my/cs/projects/Sub-Exporter/trunk/lib/Sub/Exporter/Tutorial.pod 31962 2007-07-04T02:29:46.946587Z rjbs $
11
13 What's an Exporter?
14
15 When you "use" a module, first it is required, then its "import" method
16 is called. The Perl documentation tells us that the following two
17 lines are equivalent:
18
19 use Module LIST;
20
21 BEGIN { require Module; Module->import(LIST); }
22
23 The import method is the module's exporter.
24
25 The Basics of Sub::Exporter
26
27 Sub::Exporter builds a custom exporter which can then be installed into
28 your module. It builds this method based on configuration passed to
29 its "setup_exporter" method.
30
31 A very basic use case might look like this:
32
33 package Addition;
34 use Sub::Exporter;
35 Sub::Exporter::setup_exporter({ exports => [ qw(plus) ]});
36
37 sub plus { my ($x, $y) = @_; return $x + $y; }
38
39 This would mean that when someone used your Addition module, they could
40 have its "plus" routine imported into their package:
41
42 use Addition qw(plus);
43
44 my $z = plus(2, 2); # this works, because now plus is in the main package
45
46 That syntax to set up the exporter, above, is a little verbose, so for
47 the simple case of just naming some exports, you can write this:
48
49 use Sub::Exporter -setup => { exports => [ qw(plus) ] };
50
51 ...which is the same as the original example -- except that now the
52 exporter is built and installed at compile time. Well, that and you
53 typed less.
54
55 Using Export Groups
56
57 You can specify whole groups of things that should be exportable
58 together. These are called groups. Exporter calls these tags. To
59 specify groups, you just pass a "groups" key in your exporter configu‐
60 ration:
61
62 package Food;
63 use Sub::Exporter -setup => {
64 exports => [ qw(apple banana beef fluff lox rabbit) ],
65 groups => {
66 fauna => [ qw(beef lox rabbit) ],
67 flora => [ qw(apple banana) ],
68 }
69 };
70
71 Now, to import all that delicious foreign meat, your consumer needs
72 only to write:
73
74 use Food qw(:fauna);
75 use Food qw(-fauna);
76
77 Either one of the above is acceptable. A colon is more traditional,
78 but barewords with a leading colon can't be enquoted by a fat arrow.
79 We'll see why that matters later on.
80
81 Groups can contain other groups. If you include a group name (with the
82 leading dash or colon) in a group definition, it will be expanded
83 recursively when the exporter is called. The exporter will not recurse
84 into the same group twice while expanding groups.
85
86 There are two special groups: "all" and "default". The "all" group is
87 defined by default, and contains all exportable subs. You can redefine
88 it, if you want to export only a subset when all exports are requested.
89 The "default" group is the set of routines to export when nothing spe‐
90 cific is requested. By default, there is no "default" group.
91
92 Renaming Your Imports
93
94 Sometimes you want to import something, but you don't like the name as
95 which it's imported. Sub::Exporter can rename your imports for you.
96 If you wanted to import "lox" from the Food package, but you don't like
97 the name, you could write this:
98
99 use Food lox => { -as => 'salmon' };
100
101 Now you'd get the "lox" routine, but it would be called salmon in your
102 package. You can also rename entire groups by using the "prefix"
103 option:
104
105 use Food -fauna => { -prefix => 'cute_little_' };
106
107 Now you can call your "cute_little_rabbit" routine. (You can also call
108 "cute_little_beef", but that hardly seems as enticing.)
109
110 When you define groups, you can include renaming.
111
112 use Sub::Exporter -setup => {
113 exports => [ qw(apple banana beef fluff lox rabbit) ],
114 groups => {
115 fauna => [ qw(beef lox), rabbit => { -as => 'coney' } ],
116 }
117 };
118
119 A prefix on a group like that does the right thing. This is when it's
120 useful to use a dash instead of a colon to indicate a group: you can
121 put a fat arrow between the group and its arguments, then.
122
123 use Food -fauna => { -prefix => 'lovely_' };
124
125 eat( lovely_coney ); # this works
126
127 Prefixes also apply recursively. That means that this code works:
128
129 use Sub::Exporter -setup => {
130 exports => [ qw(apple banana beef fluff lox rabbit) ],
131 groups => {
132 fauna => [ qw(beef lox), rabbit => { -as => 'coney' } ],
133 allowed => [ -fauna => { -prefix => 'willing_' }, 'banana' ],
134 }
135 };
136
137 ...
138
139 use Food -allowed => { -prefix => 'any_' };
140
141 $dinner = any_willing_coney; # yum!
142
143 Groups can also be passed a "-suffix" argument.
144
145 Finally, if the "-as" argument to an exported routine is a reference to
146 a scalar, a reference to the routine will be placed in that scalar.
147
148 Building Subroutines to Order
149
150 Sometimes, you want to export things that you don't have on hand. You
151 might want to offer customized routines built to the specification of
152 your consumer; that's just good business! With Sub::Exporter, this is
153 easy.
154
155 To offer subroutines to order, you need to provide a generator when you
156 set up your exporter. A generator is just a routine that returns a new
157 routine. perlref is talking about these when it discusses closures and
158 function templates. The canonical example of a generator builds a
159 unique incrementor; here's how you'd do that with Sub::Exporter;
160
161 package Package::Counter;
162 use Sub::Exporter -setup => {
163 exports => [ counter => sub { my $i = 0; sub { $i++ } } ],
164 groups => { default => [ qw(counter) ] },
165 };
166
167 Now anyone can use your Package::Counter module and he'll receive a
168 "counter" in his package. It will count up by one, and will never
169 interfere with anyone else's counter.
170
171 This isn't very useful, though, unless the consumer can explain what he
172 wants. This is done, in part, by supplying arguments when importing.
173 The following example shows how a generator can take and use arguments:
174
175 package Package::Counter;
176
177 sub _build_counter {
178 my ($class, $arg) = @_;
179 $arg ⎪⎪= {};
180 my $i = $arg->{start} ⎪⎪ 0;
181 return sub { $i++ };
182 }
183
184 use Sub::Exporter -setup => {
185 exports => [ counter => \'_build_counter' ],
186 groups => { default => [ qw(counter) ] },
187 };
188
189 Now, the consumer can (if he wants) specify a starting value for his
190 counter:
191
192 use Package::Counter counter => { start => 10 };
193
194 Arguments to a group are passed along to the generators of routines in
195 that group, but Sub::Exporter arguments -- anything beginning with a
196 dash -- are never passed in. When groups are nested, the arguments are
197 merged as the groups are expanded.
198
199 Notice, too, that in the example above, we gave a reference to a method
200 name rather than a method implementation. By giving the name rather
201 than the subroutine, we make it possible for subclasses of our "Pack‐
202 age::Counter" module to replace the "_build_counter" method.
203
204 When a generator is called, it is passed four parameters:
205
206 * the class on which the exporter was called
207 * the name of the export being generated (not the name it's being
208 installed as)
209 * the arguments supplied for the routine
210 * the collection of generic arguments
211
212 The third item is the last major feature that hasn't been covered.
213
214 Argument Collectors
215
216 Sometimes you will want to accept arguments once that can then be
217 available to any subroutine that you're going to export. To do this,
218 you specify collectors, like this:
219
220 use Menu::Airline
221 use Sub::Exporter -setup => {
222 exports => ... ,
223 groups => ... ,
224 collectors => [ qw(allergies ethics) ],
225 };
226
227 Collectors look like normal exports in the import call, but they don't
228 do anything but collect data which can later be passed to generators.
229 If the module was used like this:
230
231 use Menu::Airline allergies => [ qw(peanuts) ], ethics => [ qw(vegan) ];
232
233 ...the consumer would get a salad. Also, all the generators would be
234 passed, as their third argument, something like this:
235
236 { allerges => [ qw(peanuts) ], ethics => [ qw(vegan) ] }
237
238 Generators may have arguments in their definition, as well. These must
239 be code refs that perform validation of the collected values. They are
240 passed the collection value and may return true or false. If they
241 return false, the exporter will throw an exception.
242
243 Generating Many Routines in One Scope
244
245 Sometimes it's useful to have multiple routines generated in one scope.
246 This way they can share lexical data which is otherwise unavailable.
247 To do this, you can supply a generator for a group which returns a
248 hashref of names and code references. This generator is passed all the
249 usual data, and the group may receive the usual "-prefix" or "-suffix"
250 arguments.
251
253 Ricardo SIGNES, "<rjbs@cpan.org>"
254
256 * Sub::Exporter for complete documentation and references to other
257 exporters.
258
260 Copyright 2007 Ricardo SIGNES. This program is free software; you can
261 redistribute it and/or modify it under the same terms as Perl itself.
262
263
264
265perl v5.8.8 2007-07-05 Sub::Exporter::Tutorial(3)