Update site list
[p5sagit/p5-mst-13.2.git] / pod / perlmod.pod
1 =head1 NAME
2
3 perlmod - Perl modules (packages)
4
5 =head1 DESCRIPTION
6
7 =head2 Packages
8
9 Perl provides a mechanism for alternative namespaces to protect packages
10 from stomping on each other's variables.  In fact, apart from certain
11 magical variables, there's really no such thing as a global variable in
12 Perl.  The package statement declares the compilation unit as being in the
13 given namespace.  The scope of the package declaration is from the
14 declaration itself through the end of the enclosing block (the same scope
15 as the local() operator).  All further unqualified dynamic identifiers
16 will be in this namespace.  A package statement affects only dynamic
17 variables--including those you've used local() on--but I<not> lexical
18 variables created with my().  Typically it would be the first declaration
19 in a file to be included by the C<require> or C<use> operator.  You can
20 switch into a package in more than one place; it influences merely which
21 symbol table is used by the compiler for the rest of that block.  You can
22 refer to variables and filehandles in other packages by prefixing the
23 identifier with the package name and a double colon:
24 C<$Package::Variable>.  If the package name is null, the C<main> package
25 is assumed.  That is, C<$::sail> is equivalent to C<$main::sail>.
26
27 (The old package delimiter was a single quote, but double colon
28 is now the preferred delimiter, in part because it's more readable
29 to humans, and in part because it's more readable to B<emacs> macros.
30 It also makes C++ programmers feel like they know what's going on.)
31
32 Packages may be nested inside other packages: C<$OUTER::INNER::var>.  This
33 implies nothing about the order of name lookups, however.  All symbols
34 are either local to the current package, or must be fully qualified
35 from the outer package name down.  For instance, there is nowhere
36 within package C<OUTER> that C<$INNER::var> refers to C<$OUTER::INNER::var>.
37 It would treat package C<INNER> as a totally separate global package.
38
39 Only identifiers starting with letters (or underscore) are stored in a
40 package's symbol table.  All other symbols are kept in package C<main>,
41 including all of the punctuation variables like $_.  In addition, the
42 identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are
43 forced to be in package C<main>, even when used for other purposes than
44 their built-in one.  Note also that, if you have a package called C<m>,
45 C<s>, or C<y>, then you can't use the qualified form of an identifier
46 because it will be interpreted instead as a pattern match, a substitution,
47 or a translation.
48
49 (Variables beginning with underscore used to be forced into package
50 main, but we decided it was more useful for package writers to be able
51 to use leading underscore to indicate private variables and method names.
52 $_ is still global though.)
53
54 Eval()ed strings are compiled in the package in which the eval() was
55 compiled.  (Assignments to C<$SIG{}>, however, assume the signal
56 handler specified is in the C<main> package.  Qualify the signal handler
57 name if you wish to have a signal handler in a package.)  For an
58 example, examine F<perldb.pl> in the Perl library.  It initially switches
59 to the C<DB> package so that the debugger doesn't interfere with variables
60 in the script you are trying to debug.  At various points, however, it
61 temporarily switches back to the C<main> package to evaluate various
62 expressions in the context of the C<main> package (or wherever you came
63 from).  See L<perldebug>.
64
65 See L<perlsub> for other scoping issues related to my() and local(),
66 or L<perlref> regarding closures.
67
68 =head2 Symbol Tables
69
70 The symbol table for a package happens to be stored in the hash of that
71 name with two colons appended.  The main symbol table's name is thus
72 C<%main::>, or C<%::> for short.  Likewise symbol table for the nested
73 package mentioned earlier is named C<%OUTER::INNER::>.
74
75 The value in each entry of the hash is what you are referring to when you
76 use the C<*name> typeglob notation.  In fact, the following have the same
77 effect, though the first is more efficient because it does the symbol
78 table lookups at compile time:
79
80     local(*main::foo) = *main::bar; local($main::{'foo'}) =
81     $main::{'bar'};
82
83 You can use this to print out all the variables in a package, for
84 instance.  Here is F<dumpvar.pl> from the Perl library:
85
86    package dumpvar;
87    sub main::dumpvar {
88        ($package) = @_;
89        local(*stab) = eval("*${package}::");
90        while (($key,$val) = each(%stab)) {
91            local(*entry) = $val;
92            if (defined $entry) {
93                print "\$$key = '$entry'\n";
94            }
95
96            if (defined @entry) {
97                print "\@$key = (\n";
98                foreach $num ($[ .. $#entry) {
99                    print "  $num\t'",$entry[$num],"'\n";
100                }
101                print ")\n";
102            }
103
104            if ($key ne "${package}::" && defined %entry) {
105                print "\%$key = (\n";
106                foreach $key (sort keys(%entry)) {
107                    print "  $key\t'",$entry{$key},"'\n";
108                }
109                print ")\n";
110            }
111        }
112    }
113
114 Note that even though the subroutine is compiled in package C<dumpvar>,
115 the name of the subroutine is qualified so that its name is inserted
116 into package C<main>.
117
118 Assignment to a typeglob performs an aliasing operation, i.e.,
119
120     *dick = *richard;
121
122 causes variables, subroutines, and file handles accessible via the
123 identifier C<richard> to also be accessible via the identifier C<dick>.  If
124 you want to alias only a particular variable or subroutine, you can
125 assign a reference instead:
126
127     *dick = \$richard;
128
129 makes $richard and $dick the same variable, but leaves
130 @richard and @dick as separate arrays.  Tricky, eh?
131
132 This mechanism may be used to pass and return cheap references
133 into or from subroutines if you won't want to copy the whole
134 thing.
135
136     %some_hash = ();
137     *some_hash = fn( \%another_hash );
138     sub fn {
139         local *hashsym = shift;
140         # now use %hashsym normally, and you
141         # will affect the caller's %another_hash
142         my %nhash = (); # do what you want
143         return \%nhash;
144     }
145
146 On return, the reference will overwrite the hash slot in the
147 symbol table specified by the *some_hash typeglob.  This
148 is a somewhat tricky way of passing around references cheaply
149 when you won't want to have to remember to dereference variables
150 explicitly.
151
152 Another use of symbol tables is for making "constant"  scalars.
153
154     *PI = \3.14159265358979;
155
156 Now you cannot alter $PI, which is probably a good thing all in all.
157
158 You can say C<*foo{PACKAGE}> and C<*foo{NAME}> to find out what name and
159 package the *foo symbol table entry comes from.  This may be useful
160 in a subroutine which is passed typeglobs as arguments
161
162     sub identify_typeglob {
163         my $glob = shift;
164         print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n";
165     }
166     identify_typeglob *foo;
167     identify_typeglob *bar::baz;
168
169 This prints
170
171     You gave me main::foo
172     You gave me bar::baz
173
174 The *foo{THING} notation can also be used to obtain references to the
175 individual elements of *foo, see L<perlref>.
176
177 =head2 Package Constructors and Destructors
178
179 There are two special subroutine definitions that function as package
180 constructors and destructors.  These are the C<BEGIN> and C<END>
181 routines.  The C<sub> is optional for these routines.
182
183 A C<BEGIN> subroutine is executed as soon as possible, that is, the
184 moment it is completely defined, even before the rest of the containing
185 file is parsed.  You may have multiple C<BEGIN> blocks within a
186 file--they will execute in order of definition.  Because a C<BEGIN>
187 block executes immediately, it can pull in definitions of subroutines
188 and such from other files in time to be visible to the rest of the
189 file.
190
191 An C<END> subroutine is executed as late as possible, that is, when the
192 interpreter is being exited, even if it is exiting as a result of a
193 die() function.  (But not if it's is being blown out of the water by a
194 signal--you have to trap that yourself (if you can).)  You may have
195 multiple C<END> blocks within a file--they will execute in reverse
196 order of definition; that is: last in, first out (LIFO).
197
198 Inside an C<END> subroutine C<$?> contains the value that the script is
199 going to pass to C<exit()>.  You can modify C<$?> to change the exit
200 value of the script.  Beware of changing C<$?> by accident (e.g.,, by
201 running something via C<system>).
202
203 Note that when you use the B<-n> and B<-p> switches to Perl, C<BEGIN>
204 and C<END> work just as they do in B<awk>, as a degenerate case.
205
206 =head2 Perl Classes
207
208 There is no special class syntax in Perl, but a package may function
209 as a class if it provides subroutines that function as methods.  Such a
210 package may also derive some of its methods from another class package
211 by listing the other package name in its @ISA array.
212
213 For more on this, see L<perlobj>.
214
215 =head2 Perl Modules
216
217 A module is just a package that is defined in a library file of
218 the same name, and is designed to be reusable.  It may do this by
219 providing a mechanism for exporting some of its symbols into the symbol
220 table of any package using it.  Or it may function as a class
221 definition and make its semantics available implicitly through method
222 calls on the class and its objects, without explicit exportation of any
223 symbols.  Or it can do a little of both.
224
225 For example, to start a normal module called Some::Module, create
226 a file called Some/Module.pm and start with this template:
227
228     package Some::Module;  # assumes Some/Module.pm
229
230     use strict;
231
232     BEGIN {
233         use Exporter   ();
234         use vars       qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
235
236         # set the version for version checking
237         $VERSION     = 1.00;
238         # if using RCS/CVS, this may be preferred
239         $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
240
241         @ISA         = qw(Exporter);
242         @EXPORT      = qw(&func1 &func2 &func4);
243         %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
244
245         # your exported package globals go here,
246         # as well as any optionally exported functions
247         @EXPORT_OK   = qw($Var1 %Hashit &func3);
248     }
249     use vars      @EXPORT_OK;
250
251     # non-exported package globals go here
252     use vars      qw(@more $stuff);
253
254     # initalize package globals, first exported ones
255     $Var1   = '';
256     %Hashit = ();
257
258     # then the others (which are still accessible as $Some::Module::stuff)
259     $stuff  = '';
260     @more   = ();
261
262     # all file-scoped lexicals must be created before
263     # the functions below that use them.
264
265     # file-private lexicals go here
266     my $priv_var    = '';
267     my %secret_hash = ();
268
269     # here's a file-private function as a closure,
270     # callable as &$priv_func;  it cannot be prototyped.
271     my $priv_func = sub {
272         # stuff goes here.
273     };
274
275     # make all your functions, whether exported or not;
276     # remember to put something interesting in the {} stubs
277     sub func1      {}    # no prototype
278     sub func2()    {}    # proto'd void
279     sub func3($$)  {}    # proto'd to 2 scalars
280
281     # this one isn't exported, but could be called!
282     sub func4(\%)  {}    # proto'd to 1 hash ref
283
284     END { }       # module clean-up code here (global destructor)
285
286 Then go on to declare and use your variables in functions
287 without any qualifications.
288 See L<Exporter> and the I<Perl Modules File> for details on
289 mechanics and style issues in module creation.
290
291 Perl modules are included into your program by saying
292
293     use Module;
294
295 or
296
297     use Module LIST;
298
299 This is exactly equivalent to
300
301     BEGIN { require "Module.pm"; import Module; }
302
303 or
304
305     BEGIN { require "Module.pm"; import Module LIST; }
306
307 As a special case
308
309     use Module ();
310
311 is exactly equivalent to
312
313     BEGIN { require "Module.pm"; }
314
315 All Perl module files have the extension F<.pm>.  C<use> assumes this so
316 that you don't have to spell out "F<Module.pm>" in quotes.  This also
317 helps to differentiate new modules from old F<.pl> and F<.ph> files.
318 Module names are also capitalized unless they're functioning as pragmas,
319 "Pragmas" are in effect compiler directives, and are sometimes called
320 "pragmatic modules" (or even "pragmata" if you're a classicist).
321
322 Because the C<use> statement implies a C<BEGIN> block, the importation
323 of semantics happens at the moment the C<use> statement is compiled,
324 before the rest of the file is compiled.  This is how it is able
325 to function as a pragma mechanism, and also how modules are able to
326 declare subroutines that are then visible as list operators for
327 the rest of the current file.  This will not work if you use C<require>
328 instead of C<use>.  With require you can get into this problem:
329
330     require Cwd;                # make Cwd:: accessible
331     $here = Cwd::getcwd();      
332
333     use Cwd;                    # import names from Cwd::
334     $here = getcwd();
335
336     require Cwd;                # make Cwd:: accessible
337     $here = getcwd();           # oops! no main::getcwd()
338
339 In general C<use Module ();> is recommended over C<require Module;>.
340
341 Perl packages may be nested inside other package names, so we can have
342 package names containing C<::>.  But if we used that package name
343 directly as a filename it would makes for unwieldy or impossible
344 filenames on some systems.  Therefore, if a module's name is, say,
345 C<Text::Soundex>, then its definition is actually found in the library
346 file F<Text/Soundex.pm>.
347
348 Perl modules always have a F<.pm> file, but there may also be dynamically
349 linked executables or autoloaded subroutine definitions associated with
350 the module.  If so, these will be entirely transparent to the user of
351 the module.  It is the responsibility of the F<.pm> file to load (or
352 arrange to autoload) any additional functionality.  The POSIX module
353 happens to do both dynamic loading and autoloading, but the user can
354 say just C<use POSIX> to get it all.
355
356 For more information on writing extension modules, see L<perlxs>
357 and L<perlguts>.
358
359 =head1 NOTE
360
361 Perl does not enforce private and public parts of its modules as you may
362 have been used to in other languages like C++, Ada, or Modula-17.  Perl
363 doesn't have an infatuation with enforced privacy.  It would prefer
364 that you stayed out of its living room because you weren't invited, not
365 because it has a shotgun.
366
367 The module and its user have a contract, part of which is common law,
368 and part of which is "written".  Part of the common law contract is
369 that a module doesn't pollute any namespace it wasn't asked to.  The
370 written contract for the module (A.K.A. documentation) may make other
371 provisions.  But then you know when you C<use RedefineTheWorld> that
372 you're redefining the world and willing to take the consequences.
373
374 =head1 THE PERL MODULE LIBRARY
375
376 A number of modules are included the Perl distribution.  These are
377 described below, and all end in F<.pm>.  You may also discover files in
378 the library directory that end in either F<.pl> or F<.ph>.  These are old
379 libraries supplied so that old programs that use them still run.  The
380 F<.pl> files will all eventually be converted into standard modules, and
381 the F<.ph> files made by B<h2ph> will probably end up as extension modules
382 made by B<h2xs>.  (Some F<.ph> values may already be available through the
383 POSIX module.)  The B<pl2pm> file in the distribution may help in your
384 conversion, but it's just a mechanical process and therefore far from 
385 bulletproof.
386
387 =head2 Pragmatic Modules
388
389 They work somewhat like pragmas in that they tend to affect the compilation of
390 your program, and thus will usually work well only when used within a
391 C<use>, or C<no>.  Most of these are locally scoped, so an inner BLOCK
392 may countermand any of these by saying:
393
394     no integer;
395     no strict 'refs';
396
397 which lasts until the end of that BLOCK.
398
399 Unlike the pragmas that effect the C<$^H> hints variable, the C<use
400 vars> and C<use subs> declarations are not BLOCK-scoped.  They allow
401 you to pre-declare a variables or subroutines within a particular
402 I<file> rather than just a block.  Such declarations are effective
403 for the entire file for which they were declared.  You cannot rescind
404 them with C<no vars> or C<no subs>.
405
406 The following pragmas are defined (and have their own documentation).
407
408 =over 12
409
410 =item blib
411
412 manipulate @INC at compile time to use MakeMaker's uninstalled version
413 of a package
414
415 =item diagnostics
416
417 force verbose warning diagnostics
418
419 =item integer
420
421 compute arithmetic in integer instead of double
422
423 =item less
424
425 request less of something from the compiler
426
427 =item lib
428
429 manipulate @INC at compile time
430
431 =item locale
432
433 use or ignore current locale for built-in operations (see L<perllocale>)
434
435 =item ops
436
437 restrict named opcodes when compiling or running Perl code
438
439 =item overload
440
441 overload basic Perl operations
442
443 =item sigtrap
444
445 enable simple signal handling
446
447 =item strict
448
449 restrict unsafe constructs
450
451 =item subs
452
453 pre-declare sub names
454
455 =item vmsish
456
457 adopt certain VMS-specific behaviors
458
459 =item vars
460
461 pre-declare global variable names
462
463 =back
464
465 =head2 Standard Modules
466
467 Standard, bundled modules are all expected to behave in a well-defined
468 manner with respect to namespace pollution because they use the
469 Exporter module.  See their own documentation for details.
470
471 =over 12
472
473 =item AnyDBM_File
474
475 provide framework for multiple DBMs
476
477 =item AutoLoader
478
479 load functions only on demand
480
481 =item AutoSplit
482
483 split a package for autoloading
484
485 =item Benchmark
486
487 benchmark running times of code
488
489 =item CPAN
490
491 interface to Comprehensive Perl Archive Network
492
493 =item CPAN::FirstTime
494
495 create a CPAN configuration file
496
497 =item CPAN::Nox
498
499 run CPAN while avoiding compiled extensions
500
501 =item Carp
502
503 warn of errors (from perspective of caller)
504
505 =item Class::Template
506
507 struct/member template builder
508
509 =item Config
510
511 access Perl configuration information
512
513 =item Cwd
514
515 get pathname of current working directory
516
517 =item DB_File
518
519 access to Berkeley DB
520
521 =item Devel::SelfStubber
522
523 generate stubs for a SelfLoading module
524
525 =item DirHandle
526
527 supply object methods for directory handles
528
529 =item DynaLoader
530
531 dynamically load C libraries into Perl code
532
533 =item English
534
535 use nice English (or awk) names for ugly punctuation variables
536
537 =item Env
538
539 import environment variables
540
541 =item Exporter
542
543 implements default import method for modules
544
545 =item ExtUtils::Embed
546
547 utilities for embedding Perl in C/C++ applications
548
549 =item ExtUtils::Install
550
551 install files from here to there
552
553 =item ExtUtils::Liblist
554
555 determine libraries to use and how to use them
556
557 =item ExtUtils::MM_OS2
558
559 methods to override UN*X behaviour in ExtUtils::MakeMaker
560
561 =item ExtUtils::MM_Unix
562
563 methods used by ExtUtils::MakeMaker
564
565 =item ExtUtils::MM_VMS
566
567 methods to override UN*X behaviour in ExtUtils::MakeMaker
568
569 =item ExtUtils::MakeMaker
570
571 create an extension Makefile
572
573 =item ExtUtils::Manifest
574
575 utilities to write and check a MANIFEST file
576
577 =item ExtUtils::Mkbootstrap
578
579 make a bootstrap file for use by DynaLoader
580
581 =item ExtUtils::Mksymlists
582
583 write linker options files for dynamic extension
584
585 =item ExtUtils::testlib
586
587 add blib/* directories to @INC
588
589 =item Fcntl
590
591 load the C Fcntl.h defines
592
593 =item File::Basename
594
595 split a pathname into pieces
596
597 =item File::CheckTree
598
599 run many filetest checks on a tree
600
601 =item File::Compare
602
603 compare files or filehandles
604
605 =item File::Copy
606
607 copy files or filehandles
608
609 =item File::Find
610
611 traverse a file tree
612
613 =item File::Path
614
615 create or remove a series of directories
616
617 =item File::stat
618
619 by-name interface to Perl's built-in stat() functions
620
621 =item FileCache
622
623 keep more files open than the system permits
624
625 =item FileHandle
626
627 supply object methods for filehandles
628
629 =item FindBin
630
631 locate directory of original perl script
632
633 =item GDBM_File
634
635 access to the gdbm library
636
637 =item Getopt::Long
638
639 extended processing of command line options
640
641 =item Getopt::Std
642
643 process single-character switches with switch clustering
644
645 =item I18N::Collate
646
647 compare 8-bit scalar data according to the current locale
648
649 =item IO
650
651 load various IO modules
652
653 =item IO::File
654
655 supply object methods for filehandles
656
657 =item IO::Handle
658
659 supply object methods for I/O handles
660
661 =item IO::Pipe
662
663 supply object methods for pipes
664
665 =item IO::Seekable
666
667 supply seek based methods for I/O objects
668
669 =item IO::Select
670
671 OO interface to the select system call
672
673 =item IO::Socket
674
675 object interface to socket communications
676
677 =item IPC::Open2
678
679 open a process for both reading and writing
680
681 =item IPC::Open3
682
683 open a process for reading, writing, and error handling
684
685 =item Math::BigFloat
686
687 arbitrary length float math package
688
689 =item Math::BigInt
690
691 arbitrary size integer math package
692
693 =item Math::Complex
694
695 complex numbers and associated mathematical functions
696
697 =item NDBM_File
698
699 tied access to ndbm files
700
701 =item Net::Ping
702
703 Hello, anybody home?
704
705 =item Net::hostent
706
707 by-name interface to Perl's built-in gethost*() functions
708
709 =item Net::netent
710
711 by-name interface to Perl's built-in getnet*() functions
712
713 =item Net::protoent
714
715 by-name interface to Perl's built-in getproto*() functions
716
717 =item Net::servent
718
719 by-name interface to Perl's built-in getserv*() functions
720
721 =item Opcode
722
723 disable named opcodes when compiling or running perl code
724
725 =item Pod::Text
726
727 convert POD data to formatted ASCII text
728
729 =item POSIX
730
731 interface to IEEE Standard 1003.1
732
733 =item SDBM_File
734
735 tied access to sdbm files
736
737 =item Safe
738
739 compile and execute code in restricted compartments
740
741 =item Search::Dict
742
743 search for key in dictionary file
744
745 =item SelectSaver
746
747 save and restore selected file handle
748
749 =item SelfLoader
750
751 load functions only on demand
752
753 =item Shell
754
755 run shell commands transparently within perl
756
757 =item Socket
758
759 load the C socket.h defines and structure manipulators
760
761 =item Symbol
762
763 manipulate Perl symbols and their names
764
765 =item Sys::Hostname
766
767 try every conceivable way to get hostname
768
769 =item Sys::Syslog
770
771 interface to the UNIX syslog(3) calls
772
773 =item Term::Cap
774
775 termcap interface
776
777 =item Term::Complete
778
779 word completion module
780
781 =item Term::ReadLine
782
783 interface to various C<readline> packages
784
785 =item Test::Harness
786
787 run perl standard test scripts with statistics
788
789 =item Text::Abbrev
790
791 create an abbreviation table from a list
792
793 =item Text::ParseWords
794
795 parse text into an array of tokens
796
797 =item Text::Soundex
798
799 implementation of the Soundex Algorithm as described by Knuth
800
801 =item Text::Tabs
802
803 expand and unexpand tabs per the unix expand(1) and unexpand(1)
804
805 =item Text::Wrap
806
807 line wrapping to form simple paragraphs
808
809 =item Tie::Hash
810
811 base class definitions for tied hashes
812
813 =item Tie::RefHash
814
815 base class definitions for tied hashes with references as keys
816
817 =item Tie::Scalar
818
819 base class definitions for tied scalars
820
821 =item Tie::SubstrHash
822
823 fixed-table-size, fixed-key-length hashing
824
825 =item Time::Local
826
827 efficiently compute time from local and GMT time
828
829 =item Time::gmtime
830
831 by-name interface to Perl's built-in gmtime() function
832
833 =item Time::localtime
834
835 by-name interface to Perl's built-in localtime() function
836
837 =item Time::tm
838
839 internal object used by Time::gmtime and Time::localtime
840
841 =item UNIVERSAL
842
843 base class for ALL classes (blessed references)
844
845 =item User::grent
846
847 by-name interface to Perl's built-in getgr*() functions
848
849 =item User::pwent
850
851 by-name interface to Perl's built-in getpw*() functions
852
853 =back
854
855 To find out I<all> the modules installed on your system, including
856 those without documentation or outside the standard release, do this:
857
858     find `perl -e 'print "@INC"'` -name '*.pm' -print
859
860 They should all have their own documentation installed and accessible via
861 your system man(1) command.  If that fails, try the I<perldoc> program.
862
863 =head2 Extension Modules
864
865 Extension modules are written in C (or a mix of Perl and C) and get
866 dynamically loaded into Perl if and when you need them.  Supported
867 extension modules include the Socket, Fcntl, and POSIX modules.
868
869 Many popular C extension modules do not come bundled (at least, not
870 completely) due to their sizes, volatility, or simply lack of time for
871 adequate testing and configuration across the multitude of platforms on
872 which Perl was beta-tested.  You are encouraged to look for them in
873 archie(1L), the Perl FAQ or Meta-FAQ, the WWW page, and even with their
874 authors before randomly posting asking for their present condition and
875 disposition.
876
877 =head1 CPAN
878
879 CPAN stands for the Comprehensive Perl Archive Network.  This is a globally
880 replicated collection of all known Perl materials, including hundreds
881 of unbundled modules.  Here are the major categories of modules:
882
883 =over
884
885 =item *
886 Language Extensions and Documentation Tools
887
888 =item *
889 Development Support
890
891 =item *
892 Operating System Interfaces
893
894 =item *
895 Networking, Device Control (modems) and InterProcess Communication
896
897 =item *
898 Data Types and Data Type Utilities
899
900 =item *
901 Database Interfaces
902
903 =item *
904 User Interfaces
905
906 =item *
907 Interfaces to / Emulations of Other Programming Languages
908
909 =item *
910 File Names, File Systems and File Locking (see also File Handles)
911
912 =item *
913 String Processing, Language Text Processing, Parsing, and Searching
914
915 =item *
916 Option, Argument, Parameter, and Configuration File Processing
917
918 =item *
919 Internationalization and Locale
920
921 =item *
922 Authentication, Security, and Encryption
923
924 =item *
925 World Wide Web, HTML, HTTP, CGI, MIME
926
927 =item *
928 Server and Daemon Utilities
929
930 =item *
931 Archiving and Compression
932
933 =item *
934 Images, Pixmap and Bitmap Manipulation, Drawing, and Graphing
935
936 =item *
937 Mail and Usenet News
938
939 =item *
940 Control Flow Utilities (callbacks and exceptions etc)
941
942 =item *
943 File Handle and Input/Output Stream Utilities
944
945 =item *
946 Miscellaneous Modules
947
948 =back
949
950 The registered CPAN sites as of this writing include the following.
951 You should try to choose one close to you:
952
953 =over
954
955 =item *
956 Africa
957
958     South Africa    ftp://ftp.is.co.za/programming/perl/CPAN/
959
960 =item *
961 Asia
962
963     Hong Kong       ftp://ftp.hkstar.com/pub/CPAN/
964     Japan           ftp://ftp.jaist.ac.jp/pub/lang/perl/CPAN/
965                     ftp://ftp.lab.kdd.co.jp/lang/perl/CPAN/
966     South Korea     ftp://ftp.nuri.net/pub/CPAN/
967     Taiwan          ftp://dongpo.math.ncu.edu.tw/perl/CPAN/
968                     ftp://ftp.wownet.net/pub2/PERL/
969
970 =item *
971 Australasia
972
973     Australia       ftp://ftp.netinfo.com.au/pub/perl/CPAN/
974     New Zealand     ftp://ftp.tekotago.ac.nz/pub/perl/CPAN/
975
976 =item *
977 Europe
978
979     Austria         ftp://ftp.tuwien.ac.at/pub/languages/perl/CPAN/
980     Belgium         ftp://ftp.kulnet.kuleuven.ac.be/pub/mirror/CPAN/
981     Czech Republic  ftp://sunsite.mff.cuni.cz/Languages/Perl/CPAN/
982     Denmark         ftp://sunsite.auc.dk/pub/languages/perl/CPAN/
983     Finland         ftp://ftp.funet.fi/pub/languages/perl/CPAN/
984     France          ftp://ftp.ibp.fr/pub/perl/CPAN/
985                     ftp://ftp.pasteur.fr/pub/computing/unix/perl/CPAN/
986     Germany         ftp://ftp.gmd.de/packages/CPAN/
987                     ftp://ftp.leo.org/pub/comp/programming/languages/perl/CPAN/
988                     ftp://ftp.mpi-sb.mpg.de/pub/perl/CPAN/
989                     ftp://ftp.rz.ruhr-uni-bochum.de/pub/CPAN/
990                     ftp://ftp.uni-erlangen.de/pub/source/Perl/CPAN/
991                     ftp://ftp.uni-hamburg.de/pub/soft/lang/perl/CPAN/
992     Greece          ftp://ftp.ntua.gr/pub/lang/perl/
993     Hungary         ftp://ftp.kfki.hu/pub/packages/perl/CPAN/
994     Italy           ftp://cis.utovrm.it/CPAN/
995     the Netherlands ftp://ftp.cs.ruu.nl/pub/PERL/CPAN/
996                     ftp://ftp.EU.net/packages/cpan/
997     Norway          ftp://ftp.uit.no/pub/languages/perl/cpan/
998     Poland          ftp://ftp.pk.edu.pl/pub/lang/perl/CPAN/
999                     ftp://sunsite.icm.edu.pl/pub/CPAN/
1000     Portugal        ftp://ftp.ci.uminho.pt/pub/lang/perl/
1001                     ftp://ftp.telepac.pt/pub/CPAN/
1002     Russia          ftp://ftp.sai.msu.su/pub/lang/perl/CPAN/
1003     Slovenia        ftp://ftp.arnes.si/software/perl/CPAN/
1004     Spain           ftp://ftp.etse.urv.es/pub/mirror/perl/
1005                     ftp://ftp.rediris.es/mirror/CPAN/
1006     Sweden          ftp://ftp.sunet.se/pub/lang/perl/CPAN/
1007     UK              ftp://ftp.demon.co.uk/pub/mirrors/perl/CPAN/
1008                     ftp://sunsite.doc.ic.ac.uk/packages/CPAN/
1009                     ftp://unix.hensa.ac.uk/mirrors/perl-CPAN/
1010
1011 =item *
1012 North America
1013
1014     Ontario         ftp://ftp.utilis.com/public/CPAN/
1015                     ftp://enterprise.ic.gc.ca/pub/perl/CPAN/
1016     Manitoba        ftp://theory.uwinnipeg.ca/pub/CPAN/
1017     California      ftp://ftp.digital.com/pub/plan/perl/CPAN/
1018                     ftp://ftp.cdrom.com/pub/perl/CPAN/
1019     Colorado        ftp://ftp.cs.colorado.edu/pub/perl/CPAN/
1020     Florida         ftp://ftp.cis.ufl.edu/pub/perl/CPAN/
1021     Illinois        ftp://uiarchive.uiuc.edu/pub/lang/perl/CPAN/
1022     Massachusetts   ftp://ftp.iguide.com/pub/mirrors/packages/perl/CPAN/
1023     New York        ftp://ftp.rge.com/pub/languages/perl/
1024     North Carolina  ftp://ftp.duke.edu/pub/perl/
1025     Oklahoma        ftp://ftp.ou.edu/mirrors/CPAN/
1026     Oregon          http://www.perl.org/CPAN/
1027                     ftp://ftp.orst.edu/pub/packages/CPAN/
1028     Pennsylvania    ftp://ftp.epix.net/pub/languages/perl/
1029     Texas           ftp://ftp.sedl.org/pub/mirrors/CPAN/
1030                     ftp://ftp.metronet.com/pub/perl/
1031
1032 =item *
1033 South America
1034
1035     Chile           ftp://sunsite.dcc.uchile.cl/pub/Lang/perl/CPAN/
1036
1037 =back
1038
1039 For an up-to-date listing of CPAN sites,
1040 see F<http://www.perl.com/perl/CPAN> or F<ftp://ftp.perl.com/perl/>.
1041
1042 =head1 Modules: Creation, Use, and Abuse
1043
1044 (The following section is borrowed directly from Tim Bunce's modules
1045 file, available at your nearest CPAN site.)
1046
1047 Perl implements a class using a package, but the presence of a
1048 package doesn't imply the presence of a class.  A package is just a
1049 namespace.  A class is a package that provides subroutines that can be
1050 used as methods.  A method is just a subroutine that expects, as its
1051 first argument, either the name of a package (for "static" methods),
1052 or a reference to something (for "virtual" methods).
1053
1054 A module is a file that (by convention) provides a class of the same
1055 name (sans the .pm), plus an import method in that class that can be
1056 called to fetch exported symbols.  This module may implement some of
1057 its methods by loading dynamic C or C++ objects, but that should be
1058 totally transparent to the user of the module.  Likewise, the module
1059 might set up an AUTOLOAD function to slurp in subroutine definitions on
1060 demand, but this is also transparent.  Only the .pm file is required to
1061 exist.
1062
1063 =head2 Guidelines for Module Creation
1064
1065 =over 4
1066
1067 =item Do similar modules already exist in some form?
1068
1069 If so, please try to reuse the existing modules either in whole or
1070 by inheriting useful features into a new class.  If this is not
1071 practical try to get together with the module authors to work on
1072 extending or enhancing the functionality of the existing modules.
1073 A perfect example is the plethora of packages in perl4 for dealing
1074 with command line options.
1075
1076 If you are writing a module to expand an already existing set of
1077 modules, please coordinate with the author of the package.  It
1078 helps if you follow the same naming scheme and module interaction
1079 scheme as the original author.
1080
1081 =item Try to design the new module to be easy to extend and reuse.
1082
1083 Use blessed references.  Use the two argument form of bless to bless
1084 into the class name given as the first parameter of the constructor,
1085 e.g.,:
1086
1087  sub new {
1088         my $class = shift;
1089         return bless {}, $class;
1090  }
1091
1092 or even this if you'd like it to be used as either a static
1093 or a virtual method.
1094
1095  sub new {
1096         my $self  = shift;
1097         my $class = ref($self) || $self;
1098         return bless {}, $class;
1099  }
1100
1101 Pass arrays as references so more parameters can be added later
1102 (it's also faster).  Convert functions into methods where
1103 appropriate.  Split large methods into smaller more flexible ones.
1104 Inherit methods from other modules if appropriate.
1105
1106 Avoid class name tests like: C<die "Invalid" unless ref $ref eq 'FOO'>.
1107 Generally you can delete the "C<eq 'FOO'>" part with no harm at all.
1108 Let the objects look after themselves! Generally, avoid hardwired
1109 class names as far as possible.
1110
1111 Avoid C<$r-E<gt>Class::func()> where using C<@ISA=qw(... Class ...)> and
1112 C<$r-E<gt>func()> would work (see L<perlbot> for more details).
1113
1114 Use autosplit so little used or newly added functions won't be a
1115 burden to programs which don't use them. Add test functions to
1116 the module after __END__ either using AutoSplit or by saying:
1117
1118  eval join('',<main::DATA>) || die $@ unless caller();
1119
1120 Does your module pass the 'empty subclass' test? If you say
1121 "C<@SUBCLASS::ISA = qw(YOURCLASS);>" your applications should be able
1122 to use SUBCLASS in exactly the same way as YOURCLASS.  For example,
1123 does your application still work if you change:  C<$obj = new YOURCLASS;>
1124 into: C<$obj = new SUBCLASS;> ?
1125
1126 Avoid keeping any state information in your packages. It makes it
1127 difficult for multiple other packages to use yours. Keep state
1128 information in objects.
1129
1130 Always use B<-w>. Try to C<use strict;> (or C<use strict qw(...);>).
1131 Remember that you can add C<no strict qw(...);> to individual blocks
1132 of code which need less strictness. Always use B<-w>. Always use B<-w>!
1133 Follow the guidelines in the perlstyle(1) manual.
1134
1135 =item Some simple style guidelines
1136
1137 The perlstyle manual supplied with perl has many helpful points.
1138
1139 Coding style is a matter of personal taste. Many people evolve their
1140 style over several years as they learn what helps them write and
1141 maintain good code.  Here's one set of assorted suggestions that
1142 seem to be widely used by experienced developers:
1143
1144 Use underscores to separate words.  It is generally easier to read
1145 $var_names_like_this than $VarNamesLikeThis, especially for
1146 non-native speakers of English. It's also a simple rule that works
1147 consistently with VAR_NAMES_LIKE_THIS.
1148
1149 Package/Module names are an exception to this rule. Perl informally
1150 reserves lowercase module names for 'pragma' modules like integer
1151 and strict. Other modules normally begin with a capital letter and
1152 use mixed case with no underscores (need to be short and portable).
1153
1154 You may find it helpful to use letter case to indicate the scope
1155 or nature of a variable. For example:
1156
1157  $ALL_CAPS_HERE   constants only (beware clashes with perl vars)
1158  $Some_Caps_Here  package-wide global/static
1159  $no_caps_here    function scope my() or local() variables
1160
1161 Function and method names seem to work best as all lowercase.
1162 e.g.,, C<$obj-E<gt>as_string()>.
1163
1164 You can use a leading underscore to indicate that a variable or
1165 function should not be used outside the package that defined it.
1166
1167 =item Select what to export.
1168
1169 Do NOT export method names!
1170
1171 Do NOT export anything else by default without a good reason!
1172
1173 Exports pollute the namespace of the module user.  If you must
1174 export try to use @EXPORT_OK in preference to @EXPORT and avoid
1175 short or common names to reduce the risk of name clashes.
1176
1177 Generally anything not exported is still accessible from outside the
1178 module using the ModuleName::item_name (or C<$blessed_ref-E<gt>method>)
1179 syntax.  By convention you can use a leading underscore on names to
1180 indicate informally that they are 'internal' and not for public use.
1181
1182 (It is actually possible to get private functions by saying:
1183 C<my $subref = sub { ... };  &$subref;>.  But there's no way to call that
1184 directly as a method, because a method must have a name in the symbol
1185 table.)
1186
1187 As a general rule, if the module is trying to be object oriented
1188 then export nothing. If it's just a collection of functions then
1189 @EXPORT_OK anything but use @EXPORT with caution.
1190
1191 =item Select a name for the module.
1192
1193 This name should be as descriptive, accurate, and complete as
1194 possible.  Avoid any risk of ambiguity. Always try to use two or
1195 more whole words.  Generally the name should reflect what is special
1196 about what the module does rather than how it does it.  Please use
1197 nested module names to group informally or categorize a module.
1198 There should be a very good reason for a module not to have a nested name.
1199 Module names should begin with a capital letter.
1200
1201 Having 57 modules all called Sort will not make life easy for anyone
1202 (though having 23 called Sort::Quick is only marginally better :-).
1203 Imagine someone trying to install your module alongside many others.
1204 If in any doubt ask for suggestions in comp.lang.perl.misc.
1205
1206 If you are developing a suite of related modules/classes it's good
1207 practice to use nested classes with a common prefix as this will
1208 avoid namespace clashes. For example:  Xyz::Control, Xyz::View,
1209 Xyz::Model etc. Use the modules in this list as a naming guide.
1210
1211 If adding a new module to a set, follow the original author's
1212 standards for naming modules and the interface to methods in
1213 those modules.
1214
1215 To be portable each component of a module name should be limited to
1216 11 characters. If it might be used on DOS then try to ensure each is
1217 unique in the first 8 characters. Nested modules make this easier.
1218
1219 =item Have you got it right?
1220
1221 How do you know that you've made the right decisions? Have you
1222 picked an interface design that will cause problems later? Have
1223 you picked the most appropriate name? Do you have any questions?
1224
1225 The best way to know for sure, and pick up many helpful suggestions,
1226 is to ask someone who knows. Comp.lang.perl.misc is read by just about
1227 all the people who develop modules and it's the best place to ask.
1228
1229 All you need to do is post a short summary of the module, its
1230 purpose and interfaces. A few lines on each of the main methods is
1231 probably enough. (If you post the whole module it might be ignored
1232 by busy people - generally the very people you want to read it!)
1233
1234 Don't worry about posting if you can't say when the module will be
1235 ready - just say so in the message. It might be worth inviting
1236 others to help you, they may be able to complete it for you!
1237
1238 =item README and other Additional Files.
1239
1240 It's well known that software developers usually fully document the
1241 software they write. If, however, the world is in urgent need of
1242 your software and there is not enough time to write the full
1243 documentation please at least provide a README file containing:
1244
1245 =over 10
1246
1247 =item *
1248 A description of the module/package/extension etc.
1249
1250 =item *
1251 A copyright notice - see below.
1252
1253 =item *
1254 Prerequisites - what else you may need to have.
1255
1256 =item *
1257 How to build it - possible changes to Makefile.PL etc.
1258
1259 =item *
1260 How to install it.
1261
1262 =item *
1263 Recent changes in this release, especially incompatibilities
1264
1265 =item *
1266 Changes / enhancements you plan to make in the future.
1267
1268 =back
1269
1270 If the README file seems to be getting too large you may wish to
1271 split out some of the sections into separate files: INSTALL,
1272 Copying, ToDo etc.
1273
1274 =over 4
1275
1276 =item Adding a Copyright Notice.
1277
1278 How you choose to license your work is a personal decision.
1279 The general mechanism is to assert your Copyright and then make
1280 a declaration of how others may copy/use/modify your work.
1281
1282 Perl, for example, is supplied with two types of license: The GNU
1283 GPL and The Artistic License (see the files README, Copying, and
1284 Artistic).  Larry has good reasons for NOT just using the GNU GPL.
1285
1286 My personal recommendation, out of respect for Larry, Perl, and the
1287 perl community at large is to state something simply like:
1288
1289  Copyright (c) 1995 Your Name. All rights reserved.
1290  This program is free software; you can redistribute it and/or
1291  modify it under the same terms as Perl itself.
1292
1293 This statement should at least appear in the README file. You may
1294 also wish to include it in a Copying file and your source files.
1295 Remember to include the other words in addition to the Copyright.
1296
1297 =item Give the module a version/issue/release number.
1298
1299 To be fully compatible with the Exporter and MakeMaker modules you
1300 should store your module's version number in a non-my package
1301 variable called $VERSION.  This should be a floating point
1302 number with at least two digits after the decimal (i.e., hundredths,
1303 e.g, C<$VERSION = "0.01">).  Don't use a "1.3.2" style version.
1304 See Exporter.pm in Perl5.001m or later for details.
1305
1306 It may be handy to add a function or method to retrieve the number.
1307 Use the number in announcements and archive file names when
1308 releasing the module (ModuleName-1.02.tar.Z).
1309 See perldoc ExtUtils::MakeMaker.pm for details.
1310
1311 =item How to release and distribute a module.
1312
1313 It's good idea to post an announcement of the availability of your
1314 module (or the module itself if small) to the comp.lang.perl.announce
1315 Usenet newsgroup.  This will at least ensure very wide once-off
1316 distribution.
1317
1318 If possible you should place the module into a major ftp archive and
1319 include details of its location in your announcement.
1320
1321 Some notes about ftp archives: Please use a long descriptive file
1322 name which includes the version number. Most incoming directories
1323 will not be readable/listable, i.e., you won't be able to see your
1324 file after uploading it. Remember to send your email notification
1325 message as soon as possible after uploading else your file may get
1326 deleted automatically. Allow time for the file to be processed
1327 and/or check the file has been processed before announcing its
1328 location.
1329
1330 FTP Archives for Perl Modules:
1331
1332 Follow the instructions and links on
1333
1334    http://franz.ww.tu-berlin.de/modulelist
1335
1336 or upload to one of these sites:
1337
1338    ftp://franz.ww.tu-berlin.de/incoming
1339    ftp://ftp.cis.ufl.edu/incoming
1340
1341 and notify <F<upload@franz.ww.tu-berlin.de>>.
1342
1343 By using the WWW interface you can ask the Upload Server to mirror
1344 your modules from your ftp or WWW site into your own directory on
1345 CPAN!
1346
1347 Please remember to send me an updated entry for the Module list!
1348
1349 =item Take care when changing a released module.
1350
1351 Always strive to remain compatible with previous released versions
1352 (see 2.2 above) Otherwise try to add a mechanism to revert to the
1353 old behaviour if people rely on it. Document incompatible changes.
1354
1355 =back
1356
1357 =back
1358
1359 =head2 Guidelines for Converting Perl 4 Library Scripts into Modules
1360
1361 =over 4
1362
1363 =item There is no requirement to convert anything.
1364
1365 If it ain't broke, don't fix it! Perl 4 library scripts should
1366 continue to work with no problems. You may need to make some minor
1367 changes (like escaping non-array @'s in double quoted strings) but
1368 there is no need to convert a .pl file into a Module for just that.
1369
1370 =item Consider the implications.
1371
1372 All the perl applications which make use of the script will need to
1373 be changed (slightly) if the script is converted into a module.  Is
1374 it worth it unless you plan to make other changes at the same time?
1375
1376 =item Make the most of the opportunity.
1377
1378 If you are going to convert the script to a module you can use the
1379 opportunity to redesign the interface. The 'Guidelines for Module
1380 Creation' above include many of the issues you should consider.
1381
1382 =item The pl2pm utility will get you started.
1383
1384 This utility will read *.pl files (given as parameters) and write
1385 corresponding *.pm files. The pl2pm utilities does the following:
1386
1387 =over 10
1388
1389 =item *
1390 Adds the standard Module prologue lines
1391
1392 =item *
1393 Converts package specifiers from ' to ::
1394
1395 =item *
1396 Converts die(...) to croak(...)
1397
1398 =item *
1399 Several other minor changes
1400
1401 =back
1402
1403 Being a mechanical process pl2pm is not bullet proof. The converted
1404 code will need careful checking, especially any package statements.
1405 Don't delete the original .pl file till the new .pm one works!
1406
1407 =back
1408
1409 =head2 Guidelines for Reusing Application Code
1410
1411 =over 4
1412
1413 =item Complete applications rarely belong in the Perl Module Library.
1414
1415 =item Many applications contain some perl code which could be reused.
1416
1417 Help save the world! Share your code in a form that makes it easy
1418 to reuse.
1419
1420 =item Break-out the reusable code into one or more separate module files.
1421
1422 =item Take the opportunity to reconsider and redesign the interfaces.
1423
1424 =item In some cases the 'application' can then be reduced to a small
1425
1426 fragment of code built on top of the reusable modules. In these cases
1427 the application could invoked as:
1428
1429      perl -e 'use Module::Name; method(@ARGV)' ...
1430 or
1431      perl -mModule::Name ...    (in perl5.002)
1432
1433 =back