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