File: Tutorial.pod

package info (click to toggle)
libsub-exporter-perl 0.990-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 380 kB
  • sloc: perl: 2,344; makefile: 2
file content (539 lines) | stat: -rw-r--r-- 19,366 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

# PODNAME: Sub::Exporter::Tutorial
# ABSTRACT: a friendly guide to exporting with Sub::Exporter

#pod =head1 DESCRIPTION
#pod
#pod =head2 What's an Exporter?
#pod
#pod When you C<use> a module, first it is required, then its C<import> method is
#pod called.  The Perl documentation tells us that the following two lines are
#pod equivalent:
#pod
#pod   use Module LIST;
#pod
#pod   BEGIN { require Module; Module->import(LIST); }
#pod
#pod The method named C<import> is the module's I<exporter>, it exports
#pod functions and variables into its caller's namespace.
#pod
#pod =head2 The Basics of Sub::Exporter
#pod
#pod Sub::Exporter builds a custom exporter which can then be installed into your
#pod module.  It builds this method based on configuration passed to its
#pod C<setup_exporter> method.
#pod
#pod A very basic use case might look like this:
#pod
#pod   package Addition;
#pod   use Sub::Exporter;
#pod   Sub::Exporter::setup_exporter({ exports => [ qw(plus) ]});
#pod
#pod   sub plus { my ($x, $y) = @_; return $x + $y; }
#pod
#pod This would mean that when someone used your Addition module, they could have
#pod its C<plus> routine imported into their package:
#pod
#pod   use Addition qw(plus);
#pod
#pod   my $z = plus(2, 2); # this works, because now plus is in the main package
#pod
#pod That syntax to set up the exporter, above, is a little verbose, so for the
#pod simple case of just naming some exports, you can write this:
#pod
#pod   use Sub::Exporter -setup => { exports => [ qw(plus) ] };
#pod
#pod ...which is the same as the original example -- except that now the exporter is
#pod built and installed at compile time.  Well, that and you typed less.
#pod
#pod =head2 Using Export Groups
#pod
#pod You can specify whole groups of things that should be exportable together.
#pod These are called groups.  L<Exporter> calls these tags.  To specify groups, you
#pod just pass a C<groups> key in your exporter configuration:
#pod
#pod   package Food;
#pod   use Sub::Exporter -setup => {
#pod     exports => [ qw(apple banana beef fluff lox rabbit) ],
#pod     groups  => {
#pod       fauna  => [ qw(beef lox rabbit) ],
#pod       flora  => [ qw(apple banana) ],
#pod     }
#pod   };
#pod
#pod Now, to import all that delicious foreign meat, your consumer needs only to
#pod write:
#pod
#pod   use Food qw(:fauna);
#pod   use Food qw(-fauna);
#pod
#pod Either one of the above is acceptable.  A colon is more traditional, but
#pod barewords with a leading colon can't be enquoted by a fat arrow.  We'll see why
#pod that matters later on.
#pod
#pod Groups can contain other groups.  If you include a group name (with the leading
#pod dash or colon) in a group definition, it will be expanded recursively when the
#pod exporter is called.  The exporter will B<not> recurse into the same group twice
#pod while expanding groups.
#pod
#pod There are two special groups:  C<all> and C<default>.  The C<all> group is
#pod defined for you and contains all exportable subs.  You can redefine it,
#pod if you want to export only a subset when all exports are requested.  The
#pod C<default> group is the set of routines to export when nothing specific is
#pod requested.  By default, there is no C<default> group.
#pod
#pod =head2 Renaming Your Imports
#pod
#pod Sometimes you want to import something, but you don't like the name as which
#pod it's imported.  Sub::Exporter can rename your imports for you.  If you wanted
#pod to import C<lox> from the Food package, but you don't like the name, you could
#pod write this:
#pod
#pod   use Food lox => { -as => 'salmon' };
#pod
#pod Now you'd get the C<lox> routine, but it would be called salmon in your
#pod package.  You can also rename entire groups by using the C<prefix> option:
#pod
#pod   use Food -fauna => { -prefix => 'cute_little_' };
#pod
#pod Now you can call your C<cute_little_rabbit> routine.  (You can also call
#pod C<cute_little_beef>, but that hardly seems as enticing.)
#pod
#pod When you define groups, you can include renaming.
#pod
#pod   use Sub::Exporter -setup => {
#pod     exports => [ qw(apple banana beef fluff lox rabbit) ],
#pod     groups  => {
#pod       fauna  => [ qw(beef lox), rabbit => { -as => 'coney' } ],
#pod     }
#pod   };
#pod
#pod A prefix on a group like that does the right thing.  This is when it's useful
#pod to use a dash instead of a colon to indicate a group: you can put a fat arrow
#pod between the group and its arguments, then.
#pod
#pod   use Food -fauna => { -prefix => 'lovely_' };
#pod
#pod   eat( lovely_coney ); # this works
#pod
#pod Prefixes also apply recursively.  That means that this code works:
#pod
#pod   use Sub::Exporter -setup => {
#pod     exports => [ qw(apple banana beef fluff lox rabbit) ],
#pod     groups  => {
#pod       fauna   => [ qw(beef lox), rabbit => { -as => 'coney' } ],
#pod       allowed => [ -fauna => { -prefix => 'willing_' }, 'banana' ],
#pod     }
#pod   };
#pod
#pod   ...
#pod
#pod   use Food -allowed => { -prefix => 'any_' };
#pod
#pod   $dinner = any_willing_coney; # yum!
#pod
#pod Groups can also be passed a C<-suffix> argument.
#pod
#pod Finally, if the C<-as> argument to an exported routine is a reference to a
#pod scalar, a reference to the routine will be placed in that scalar.
#pod
#pod =head2 Building Subroutines to Order
#pod
#pod Sometimes, you want to export things that you don't have on hand.  You might
#pod want to offer customized routines built to the specification of your consumer;
#pod that's just good business!  With Sub::Exporter, this is easy.
#pod
#pod To offer subroutines to order, you need to provide a generator when you set up
#pod your exporter.  A generator is just a routine that returns a new routine.
#pod L<perlref> is talking about these when it discusses closures and function
#pod templates. The canonical example of a generator builds a unique incrementor;
#pod here's how you'd do that with Sub::Exporter;
#pod
#pod   package Package::Counter;
#pod   use Sub::Exporter -setup => {
#pod     exports => [ counter => sub { my $i = 0; sub { $i++ } } ],
#pod     groups  => { default => [ qw(counter) ] },
#pod   };
#pod
#pod Now anyone can use your Package::Counter module and he'll receive a C<counter>
#pod in his package.  It will count up by one, and will never interfere with anyone
#pod else's counter.
#pod
#pod This isn't very useful, though, unless the consumer can explain what he wants.
#pod This is done, in part, by supplying arguments when importing.  The following
#pod example shows how a generator can take and use arguments:
#pod
#pod   package Package::Counter;
#pod
#pod   sub _build_counter {
#pod     my ($class, $name, $arg) = @_;
#pod     $arg ||= {};
#pod     my $i = $arg->{start} || 0;
#pod     return sub { $i++ };
#pod   }
#pod
#pod   use Sub::Exporter -setup => {
#pod     exports => [ counter => \'_build_counter' ],
#pod     groups  => { default => [ qw(counter) ] },
#pod   };
#pod
#pod Now, the consumer can (if he wants) specify a starting value for his counter:
#pod
#pod   use Package::Counter counter => { start => 10 };
#pod
#pod Arguments to a group are passed along to the generators of routines in that
#pod group, but Sub::Exporter arguments -- anything beginning with a dash -- are
#pod never passed in.  When groups are nested, the arguments are merged as the
#pod groups are expanded.
#pod
#pod Notice, too, that in the example above, we gave a reference to a method I<name>
#pod rather than a method I<implementation>.  By giving the name rather than the
#pod subroutine, we make it possible for subclasses of our "Package::Counter" module
#pod to replace the C<_build_counter> method.
#pod
#pod When a generator is called, it is passed four parameters:
#pod
#pod =over
#pod
#pod =item * the invocant on which the exporter was called
#pod
#pod =item * the name of the export being generated (not the name it's being installed as)
#pod
#pod =item * the arguments supplied for the routine
#pod
#pod =item * the collection of generic arguments
#pod
#pod =back
#pod
#pod The fourth item is the last major feature that hasn't been covered.
#pod
#pod =head2 Argument Collectors
#pod
#pod Sometimes you will want to accept arguments once that can then be available to
#pod any subroutine that you're going to export.  To do this, you specify
#pod collectors, like this:
#pod
#pod   package Menu::Airline
#pod   use Sub::Exporter -setup => {
#pod     exports =>  ... ,
#pod     groups  =>  ... ,
#pod     collectors => [ qw(allergies ethics) ],
#pod   };
#pod
#pod Collectors look like normal exports in the import call, but they don't do
#pod anything but collect data which can later be passed to generators.  If the
#pod module was used like this:
#pod
#pod   use Menu::Airline allergies => [ qw(peanuts) ], ethics => [ qw(vegan) ];
#pod
#pod ...the consumer would get a salad.  Also, all the generators would be passed,
#pod as their fourth argument, something like this:
#pod
#pod   { allerges => [ qw(peanuts) ], ethics => [ qw(vegan) ] }
#pod
#pod Generators may have arguments in their definition, as well.  These must be code
#pod refs that perform validation of the collected values.  They are passed the
#pod collection value and may return true or false.  If they return false, the
#pod exporter will throw an exception.
#pod
#pod =head2 Generating Many Routines in One Scope
#pod
#pod Sometimes it's useful to have multiple routines generated in one scope.  This
#pod way they can share lexical data which is otherwise unavailable.  To do this,
#pod you can supply a generator for a group which returns a hashref of names and
#pod code references.  This generator is passed all the usual data, and the group
#pod may receive the usual C<-prefix> or C<-suffix> arguments.
#pod
#pod =head1 SEE ALSO
#pod
#pod =for :list
#pod * L<Sub::Exporter> for complete documentation and references to other exporters

__END__

=pod

=encoding UTF-8

=head1 NAME

Sub::Exporter::Tutorial - a friendly guide to exporting with Sub::Exporter

=head1 VERSION

version 0.990

=head1 DESCRIPTION

=head2 What's an Exporter?

When you C<use> a module, first it is required, then its C<import> method is
called.  The Perl documentation tells us that the following two lines are
equivalent:

  use Module LIST;

  BEGIN { require Module; Module->import(LIST); }

The method named C<import> is the module's I<exporter>, it exports
functions and variables into its caller's namespace.

=head2 The Basics of Sub::Exporter

Sub::Exporter builds a custom exporter which can then be installed into your
module.  It builds this method based on configuration passed to its
C<setup_exporter> method.

A very basic use case might look like this:

  package Addition;
  use Sub::Exporter;
  Sub::Exporter::setup_exporter({ exports => [ qw(plus) ]});

  sub plus { my ($x, $y) = @_; return $x + $y; }

This would mean that when someone used your Addition module, they could have
its C<plus> routine imported into their package:

  use Addition qw(plus);

  my $z = plus(2, 2); # this works, because now plus is in the main package

That syntax to set up the exporter, above, is a little verbose, so for the
simple case of just naming some exports, you can write this:

  use Sub::Exporter -setup => { exports => [ qw(plus) ] };

...which is the same as the original example -- except that now the exporter is
built and installed at compile time.  Well, that and you typed less.

=head2 Using Export Groups

You can specify whole groups of things that should be exportable together.
These are called groups.  L<Exporter> calls these tags.  To specify groups, you
just pass a C<groups> key in your exporter configuration:

  package Food;
  use Sub::Exporter -setup => {
    exports => [ qw(apple banana beef fluff lox rabbit) ],
    groups  => {
      fauna  => [ qw(beef lox rabbit) ],
      flora  => [ qw(apple banana) ],
    }
  };

Now, to import all that delicious foreign meat, your consumer needs only to
write:

  use Food qw(:fauna);
  use Food qw(-fauna);

Either one of the above is acceptable.  A colon is more traditional, but
barewords with a leading colon can't be enquoted by a fat arrow.  We'll see why
that matters later on.

Groups can contain other groups.  If you include a group name (with the leading
dash or colon) in a group definition, it will be expanded recursively when the
exporter is called.  The exporter will B<not> recurse into the same group twice
while expanding groups.

There are two special groups:  C<all> and C<default>.  The C<all> group is
defined for you and contains all exportable subs.  You can redefine it,
if you want to export only a subset when all exports are requested.  The
C<default> group is the set of routines to export when nothing specific is
requested.  By default, there is no C<default> group.

=head2 Renaming Your Imports

Sometimes you want to import something, but you don't like the name as which
it's imported.  Sub::Exporter can rename your imports for you.  If you wanted
to import C<lox> from the Food package, but you don't like the name, you could
write this:

  use Food lox => { -as => 'salmon' };

Now you'd get the C<lox> routine, but it would be called salmon in your
package.  You can also rename entire groups by using the C<prefix> option:

  use Food -fauna => { -prefix => 'cute_little_' };

Now you can call your C<cute_little_rabbit> routine.  (You can also call
C<cute_little_beef>, but that hardly seems as enticing.)

When you define groups, you can include renaming.

  use Sub::Exporter -setup => {
    exports => [ qw(apple banana beef fluff lox rabbit) ],
    groups  => {
      fauna  => [ qw(beef lox), rabbit => { -as => 'coney' } ],
    }
  };

A prefix on a group like that does the right thing.  This is when it's useful
to use a dash instead of a colon to indicate a group: you can put a fat arrow
between the group and its arguments, then.

  use Food -fauna => { -prefix => 'lovely_' };

  eat( lovely_coney ); # this works

Prefixes also apply recursively.  That means that this code works:

  use Sub::Exporter -setup => {
    exports => [ qw(apple banana beef fluff lox rabbit) ],
    groups  => {
      fauna   => [ qw(beef lox), rabbit => { -as => 'coney' } ],
      allowed => [ -fauna => { -prefix => 'willing_' }, 'banana' ],
    }
  };

  ...

  use Food -allowed => { -prefix => 'any_' };

  $dinner = any_willing_coney; # yum!

Groups can also be passed a C<-suffix> argument.

Finally, if the C<-as> argument to an exported routine is a reference to a
scalar, a reference to the routine will be placed in that scalar.

=head2 Building Subroutines to Order

Sometimes, you want to export things that you don't have on hand.  You might
want to offer customized routines built to the specification of your consumer;
that's just good business!  With Sub::Exporter, this is easy.

To offer subroutines to order, you need to provide a generator when you set up
your exporter.  A generator is just a routine that returns a new routine.
L<perlref> is talking about these when it discusses closures and function
templates. The canonical example of a generator builds a unique incrementor;
here's how you'd do that with Sub::Exporter;

  package Package::Counter;
  use Sub::Exporter -setup => {
    exports => [ counter => sub { my $i = 0; sub { $i++ } } ],
    groups  => { default => [ qw(counter) ] },
  };

Now anyone can use your Package::Counter module and he'll receive a C<counter>
in his package.  It will count up by one, and will never interfere with anyone
else's counter.

This isn't very useful, though, unless the consumer can explain what he wants.
This is done, in part, by supplying arguments when importing.  The following
example shows how a generator can take and use arguments:

  package Package::Counter;

  sub _build_counter {
    my ($class, $name, $arg) = @_;
    $arg ||= {};
    my $i = $arg->{start} || 0;
    return sub { $i++ };
  }

  use Sub::Exporter -setup => {
    exports => [ counter => \'_build_counter' ],
    groups  => { default => [ qw(counter) ] },
  };

Now, the consumer can (if he wants) specify a starting value for his counter:

  use Package::Counter counter => { start => 10 };

Arguments to a group are passed along to the generators of routines in that
group, but Sub::Exporter arguments -- anything beginning with a dash -- are
never passed in.  When groups are nested, the arguments are merged as the
groups are expanded.

Notice, too, that in the example above, we gave a reference to a method I<name>
rather than a method I<implementation>.  By giving the name rather than the
subroutine, we make it possible for subclasses of our "Package::Counter" module
to replace the C<_build_counter> method.

When a generator is called, it is passed four parameters:

=over

=item * the invocant on which the exporter was called

=item * the name of the export being generated (not the name it's being installed as)

=item * the arguments supplied for the routine

=item * the collection of generic arguments

=back

The fourth item is the last major feature that hasn't been covered.

=head2 Argument Collectors

Sometimes you will want to accept arguments once that can then be available to
any subroutine that you're going to export.  To do this, you specify
collectors, like this:

  package Menu::Airline
  use Sub::Exporter -setup => {
    exports =>  ... ,
    groups  =>  ... ,
    collectors => [ qw(allergies ethics) ],
  };

Collectors look like normal exports in the import call, but they don't do
anything but collect data which can later be passed to generators.  If the
module was used like this:

  use Menu::Airline allergies => [ qw(peanuts) ], ethics => [ qw(vegan) ];

...the consumer would get a salad.  Also, all the generators would be passed,
as their fourth argument, something like this:

  { allerges => [ qw(peanuts) ], ethics => [ qw(vegan) ] }

Generators may have arguments in their definition, as well.  These must be code
refs that perform validation of the collected values.  They are passed the
collection value and may return true or false.  If they return false, the
exporter will throw an exception.

=head2 Generating Many Routines in One Scope

Sometimes it's useful to have multiple routines generated in one scope.  This
way they can share lexical data which is otherwise unavailable.  To do this,
you can supply a generator for a group which returns a hashref of names and
code references.  This generator is passed all the usual data, and the group
may receive the usual C<-prefix> or C<-suffix> arguments.

=head1 PERL VERSION

This library should run on perls released even a long time ago.  It should
work on any version of perl released in the last five years.

Although it may work on older versions of perl, no guarantee is made that the
minimum required version will not be increased.  The version may be increased
for any reason, and there is no promise that patches will be accepted to
lower the minimum required perl.

=head1 SEE ALSO

=over 4

=item *

L<Sub::Exporter> for complete documentation and references to other exporters

=back

=head1 AUTHOR

Ricardo Signes <cpan@semiotic.systems>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2007 by Ricardo Signes.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut