1Sub::Exporter::TutorialU(s3e)r Contributed Perl DocumentaStuibo:n:Exporter::Tutorial(3)
2
3
4

NAME

6       Sub::Exporter::Tutorial - a friendly guide to exporting with
7       Sub::Exporter
8

DESCRIPTION

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

AUTHOR

246       Ricardo SIGNES, "<rjbs@cpan.org>"
247

SEE ALSO

249       ·   Sub::Exporter for complete documentation and references to other
250           exporters.
251
253       Copyright 2007 Ricardo SIGNES.  This program is free software;  you can
254       redistribute it and/or modify it under the same terms as Perl itself.
255
256
257
258perl v5.10.1                      2008-11-21        Sub::Exporter::Tutorial(3)
Impressum