c2b1f6c9611e0d122ba62cb9b7e4f80cebae2141
[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 associative
71 array of that name appended with two colons.  The main symbol table's
72 name is thus C<%main::>, or C<%::> for short.  Likewise symbol table for
73 the nested package mentioned earlier is named C<%OUTER::INNER::>.
74
75 The value in each entry of the associative array is what you are referring
76 to when you use the C<*name> typeglob notation.  In fact, the following
77 have the same effect, though the first is more efficient because it does
78 the symbol 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 Fred, create
226 a file called Fred.pm and put this at the start of it:
227
228     package      Fred;
229     use          strict;
230     use          Exporter ();
231     use          vars qw(@ISA @EXPORT @EXPORT_OK);
232     @ISA       = qw(Exporter);
233     @EXPORT    = qw(&func1 &func2);
234     @EXPORT_OK = qw($sally @listabob %harry &func3);
235     use          vars qw($sally @listabob %harry);
236
237 Then go on to declare and use your variables in functions
238 without any qualifications.
239 See L<Exporter> and the I<Perl Modules File> for details on
240 mechanics and style issues in module creation.
241
242 Perl modules are included into your program by saying
243
244     use Module;
245
246 or
247
248     use Module LIST;
249
250 This is exactly equivalent to
251
252     BEGIN { require "Module.pm"; import Module; }
253
254 or
255
256     BEGIN { require "Module.pm"; import Module LIST; }
257
258 As a special case
259
260     use Module ();
261
262 is exactly equivalent to
263
264     BEGIN { require "Module.pm"; }
265
266 All Perl module files have the extension F<.pm>.  C<use> assumes this so
267 that you don't have to spell out "F<Module.pm>" in quotes.  This also
268 helps to differentiate new modules from old F<.pl> and F<.ph> files.
269 Module names are also capitalized unless they're functioning as pragmas,
270 "Pragmas" are in effect compiler directives, and are sometimes called
271 "pragmatic modules" (or even "pragmata" if you're a classicist).
272
273 Because the C<use> statement implies a C<BEGIN> block, the importation
274 of semantics happens at the moment the C<use> statement is compiled,
275 before the rest of the file is compiled.  This is how it is able
276 to function as a pragma mechanism, and also how modules are able to
277 declare subroutines that are then visible as list operators for
278 the rest of the current file.  This will not work if you use C<require>
279 instead of C<use>.  With require you can get into this problem:
280
281     require Cwd;                # make Cwd:: accessible
282     $here = Cwd::getcwd();      
283
284     use Cwd;                    # import names from Cwd::
285     $here = getcwd();
286
287     require Cwd;                # make Cwd:: accessible
288     $here = getcwd();           # oops! no main::getcwd()
289
290 In general C<use Module ();> is recommended over C<require Module;>.
291
292 Perl packages may be nested inside other package names, so we can have
293 package names containing C<::>.  But if we used that package name
294 directly as a filename it would makes for unwieldy or impossible
295 filenames on some systems.  Therefore, if a module's name is, say,
296 C<Text::Soundex>, then its definition is actually found in the library
297 file F<Text/Soundex.pm>.
298
299 Perl modules always have a F<.pm> file, but there may also be dynamically
300 linked executables or autoloaded subroutine definitions associated with
301 the module.  If so, these will be entirely transparent to the user of
302 the module.  It is the responsibility of the F<.pm> file to load (or
303 arrange to autoload) any additional functionality.  The POSIX module
304 happens to do both dynamic loading and autoloading, but the user can
305 say just C<use POSIX> to get it all.
306
307 For more information on writing extension modules, see L<perlxs>
308 and L<perlguts>.
309
310 =head1 NOTE
311
312 Perl does not enforce private and public parts of its modules as you may
313 have been used to in other languages like C++, Ada, or Modula-17.  Perl
314 doesn't have an infatuation with enforced privacy.  It would prefer
315 that you stayed out of its living room because you weren't invited, not
316 because it has a shotgun.
317
318 The module and its user have a contract, part of which is common law,
319 and part of which is "written".  Part of the common law contract is
320 that a module doesn't pollute any namespace it wasn't asked to.  The
321 written contract for the module (A.K.A. documentation) may make other
322 provisions.  But then you know when you C<use RedefineTheWorld> that
323 you're redefining the world and willing to take the consequences.
324
325 =head1 THE PERL MODULE LIBRARY
326
327 A number of modules are included the Perl distribution.  These are
328 described below, and all end in F<.pm>.  You may also discover files in
329 the library directory that end in either F<.pl> or F<.ph>.  These are old
330 libraries supplied so that old programs that use them still run.  The
331 F<.pl> files will all eventually be converted into standard modules, and
332 the F<.ph> files made by B<h2ph> will probably end up as extension modules
333 made by B<h2xs>.  (Some F<.ph> values may already be available through the
334 POSIX module.)  The B<pl2pm> file in the distribution may help in your
335 conversion, but it's just a mechanical process, so is far from bulletproof.
336
337 =head2 Pragmatic Modules
338
339 They work somewhat like pragmas in that they tend to affect the compilation of
340 your program, and thus will usually work well only when used within a
341 C<use>, or C<no>.  Most of these are locally scoped, so an inner BLOCK
342 may countermand any of these by saying:
343
344     no integer;
345     no strict 'refs';
346
347 which lasts until the end of that BLOCK.
348
349 Unlike the pragmas that effect the C<$^H> hints variable, the C<use
350 vars> and C<use subs> declarations are not BLOCK-scoped.  They allow
351 you to pre-declare a variables or subroutines within a particular
352 <I>file</I> rather than just a block.  Such declarations are effective
353 for the entire file for which they were declared.  You cannot rescind
354 them with C<no vars> or C<no subs>.
355
356 The following pragmas are defined (and have their own documentation).
357
358 =over 12
359
360 =item blib
361
362 manipulate @INC at compile time to use MakeMaker's uninstalled version
363 of a package
364
365 =item diagnostics
366
367 force verbose warning diagnostics
368
369 =item integer
370
371 compute arithmetic in integer instead of double
372
373 =item less
374
375 request less of something from the compiler
376
377 =item lib
378
379 manipulate @INC at compile time
380
381 =item locale
382
383 use or ignore current locale for built-in operations (see L<perllocale>)
384
385 =item ops
386
387 restrict named opcodes when compiling or running Perl code
388
389 =item overload
390
391 overload basic Perl operations
392
393 =item sigtrap
394
395 enable simple signal handling
396
397 =item strict
398
399 restrict unsafe constructs
400
401 =item subs
402
403 pre-declare sub names
404
405 =item vars
406
407 pre-declare global variable names
408
409 =back
410
411 =head2 Standard Modules
412
413 Standard, bundled modules are all expected to behave in a well-defined
414 manner with respect to namespace pollution because they use the
415 Exporter module.  See their own documentation for details.
416
417 =over 12
418
419 =item AnyDBM_File
420
421 provide framework for multiple DBMs
422
423 =item AutoLoader
424
425 load functions only on demand
426
427 =item AutoSplit
428
429 split a package for autoloading
430
431 =item Benchmark
432
433 benchmark running times of code
434
435 =item CPAN
436
437 interface to Comprehensive Perl Archive Network
438
439 =item CPAN::FirstTime
440
441 create a CPAN configuration file
442
443 =item CPAN::Nox
444
445 run CPAN while avoiding compiled extensions
446
447 =item Carp
448
449 warn of errors (from perspective of caller)
450
451 =item Class::Template
452
453 struct/member template builder
454
455 =item Config
456
457 access Perl configuration information
458
459 =item Cwd
460
461 get pathname of current working directory
462
463 =item DB_File
464
465 access to Berkeley DB
466
467 =item Devel::SelfStubber
468
469 generate stubs for a SelfLoading module
470
471 =item DirHandle
472
473 supply object methods for directory handles
474
475 =item DynaLoader
476
477 dynamically load C libraries into Perl code
478
479 =item English
480
481 use nice English (or awk) names for ugly punctuation variables
482
483 =item Env
484
485 import environment variables
486
487 =item Exporter
488
489 implements default import method for modules
490
491 =item ExtUtils::Embed
492
493 utilities for embedding Perl in C/C++ applications
494
495 =item ExtUtils::Install
496
497 install files from here to there
498
499 =item ExtUtils::Liblist
500
501 determine libraries to use and how to use them
502
503 =item ExtUtils::MM_OS2
504
505 methods to override UN*X behaviour in ExtUtils::MakeMaker
506
507 =item ExtUtils::MM_Unix
508
509 methods used by ExtUtils::MakeMaker
510
511 =item ExtUtils::MM_VMS
512
513 methods to override UN*X behaviour in ExtUtils::MakeMaker
514
515 =item ExtUtils::MakeMaker
516
517 create an extension Makefile
518
519 =item ExtUtils::Manifest
520
521 utilities to write and check a MANIFEST file
522
523 =item ExtUtils::Mkbootstrap
524
525 make a bootstrap file for use by DynaLoader
526
527 =item ExtUtils::Mksymlists
528
529 write linker options files for dynamic extension
530
531 =item ExtUtils::testlib
532
533 add blib/* directories to @INC
534
535 =item Fatal
536
537 replace functions with equivalents which succeed or die
538
539 =item Fcntl
540
541 load the C Fcntl.h defines
542
543 =item File::Basename
544
545 split a pathname into pieces
546
547 =item File::CheckTree
548
549 run many filetest checks on a tree
550
551 =item File::Compare
552
553 compare files or filehandles
554
555 =item File::Copy
556
557 copy files or filehandles
558
559 =item File::Find
560
561 traverse a file tree
562
563 =item File::Path
564
565 create or remove a series of directories
566
567 =item File::stat
568
569 by-name interface to Perl's built-in stat() functions
570
571 =item FileCache
572
573 keep more files open than the system permits
574
575 =item FileHandle
576
577 supply object methods for filehandles
578
579 =item FindBin
580
581 locate directory of original perl script
582
583 =item GDBM_File
584
585 access to the gdbm library
586
587 =item Getopt::Long
588
589 extended processing of command line options
590
591 =item Getopt::Std
592
593 process single-character switches with switch clustering
594
595 =item I18N::Collate
596
597 compare 8-bit scalar data according to the current locale
598
599 =item IO
600
601 load various IO modules
602
603 =item IO::File
604
605 supply object methods for filehandles
606
607 =item IO::Handle
608
609 supply object methods for I/O handles
610
611 =item IO::Pipe
612
613 supply object methods for pipes
614
615 =item IO::Seekable
616
617 supply seek based methods for I/O objects
618
619 =item IO::Select
620
621 OO interface to the select system call
622
623 =item IO::Socket
624
625 object interface to socket communications
626
627 =item IPC::Open2
628
629 open a process for both reading and writing
630
631 =item IPC::Open3
632
633 open a process for reading, writing, and error handling
634
635 =item Math::BigFloat
636
637 arbitrary length float math package
638
639 =item Math::BigInt
640
641 arbitrary size integer math package
642
643 =item Math::Complex
644
645 complex numbers and associated mathematical functions
646
647 =item NDBM_File
648
649 tied access to ndbm files
650
651 =item Net::Ping
652
653 Hello, anybody home?
654
655 =item Net::hostent
656
657 by-name interface to Perl's built-in gethost*() functions
658
659 =item Net::netent
660
661 by-name interface to Perl's built-in getnet*() functions
662
663 =item Net::protoent
664
665 by-name interface to Perl's built-in getproto*() functions
666
667 =item Net::servent
668
669 by-name interface to Perl's built-in getserv*() functions
670
671 =item Opcode
672
673 disable named opcodes when compiling or running perl code
674
675 =item Pod::Text
676
677 convert POD data to formatted ASCII text
678
679 =item POSIX
680
681 interface to IEEE Standard 1003.1
682
683 =item SDBM_File
684
685 tied access to sdbm files
686
687 =item Safe
688
689 compile and execute code in restricted compartments
690
691 =item Search::Dict
692
693 search for key in dictionary file
694
695 =item SelectSaver
696
697 save and restore selected file handle
698
699 =item SelfLoader
700
701 load functions only on demand
702
703 =item Shell
704
705 run shell commands transparently within perl
706
707 =item Socket
708
709 load the C socket.h defines and structure manipulators
710
711 =item Symbol
712
713 manipulate Perl symbols and their names
714
715 =item Sys::Hostname
716
717 try every conceivable way to get hostname
718
719 =item Sys::Syslog
720
721 interface to the UNIX syslog(3) calls
722
723 =item Term::Cap
724
725 termcap interface
726
727 =item Term::Complete
728
729 word completion module
730
731 =item Term::ReadLine
732
733 interface to various C<readline> packages
734
735 =item Test::Harness
736
737 run perl standard test scripts with statistics
738
739 =item Text::Abbrev
740
741 create an abbreviation table from a list
742
743 =item Text::ParseWords
744
745 parse text into an array of tokens
746
747 =item Text::Soundex
748
749 implementation of the Soundex Algorithm as described by Knuth
750
751 =item Text::Tabs
752
753 expand and unexpand tabs per the unix expand(1) and unexpand(1)
754
755 =item Text::Wrap
756
757 line wrapping to form simple paragraphs
758
759 =item Tie::Hash
760
761 base class definitions for tied hashes
762
763 =item Tie::RefHash
764
765 base class definitions for tied hashes with references as keys
766
767 =item Tie::Scalar
768
769 base class definitions for tied scalars
770
771 =item Tie::SubstrHash
772
773 fixed-table-size, fixed-key-length hashing
774
775 =item Time::Local
776
777 efficiently compute time from local and GMT time
778
779 =item Time::gmtime
780
781 by-name interface to Perl's built-in gmtime() function
782
783 =item Time::localtime
784
785 by-name interface to Perl's built-in localtime() function
786
787 =item Time::tm
788
789 internal object used by Time::gmtime and Time::localtime
790
791 =item UNIVERSAL
792
793 base class for ALL classes (blessed references)
794
795 =item User::grent
796
797 by-name interface to Perl's built-in getgr*() functions
798
799 =item User::pwent
800
801 by-name interface to Perl's built-in getpw*() functions
802
803 =back
804
805 To find out I<all> the modules installed on your system, including
806 those without documentation or outside the standard release, do this:
807
808     find `perl -e 'print "@INC"'` -name '*.pm' -print
809
810 They should all have their own documentation installed and accessible via
811 your system man(1) command.  If that fails, try the I<perldoc> program.
812
813 =head2 Extension Modules
814
815 Extension modules are written in C (or a mix of Perl and C) and get
816 dynamically loaded into Perl if and when you need them.  Supported
817 extension modules include the Socket, Fcntl, and POSIX modules.
818
819 Many popular C extension modules do not come bundled (at least, not
820 completely) due to their sizes, volatility, or simply lack of time for
821 adequate testing and configuration across the multitude of platforms on
822 which Perl was beta-tested.  You are encouraged to look for them in
823 archie(1L), the Perl FAQ or Meta-FAQ, the WWW page, and even with their
824 authors before randomly posting asking for their present condition and
825 disposition.
826
827 =head1 CPAN
828
829 CPAN stands for the Comprehensive Perl Archive Network.  This is a globally
830 replicated collection of all known Perl materials, including hundreds
831 of unbundled modules.  Here are the major categories of modules:
832
833 =over
834
835 =item *
836 Language Extensions and Documentation Tools
837
838 =item *
839 Development Support
840
841 =item *
842 Operating System Interfaces
843
844 =item *
845 Networking, Device Control (modems) and InterProcess Communication
846
847 =item *
848 Data Types and Data Type Utilities
849
850 =item *
851 Database Interfaces
852
853 =item *
854 User Interfaces
855
856 =item *
857 Interfaces to / Emulations of Other Programming Languages
858
859 =item *
860 File Names, File Systems and File Locking (see also File Handles)
861
862 =item *
863 String Processing, Language Text Processing, Parsing, and Searching
864
865 =item *
866 Option, Argument, Parameter, and Configuration File Processing
867
868 =item *
869 Internationalization and Locale
870
871 =item *
872 Authentication, Security, and Encryption
873
874 =item *
875 World Wide Web, HTML, HTTP, CGI, MIME
876
877 =item *
878 Server and Daemon Utilities
879
880 =item *
881 Archiving and Compression
882
883 =item *
884 Images, Pixmap and Bitmap Manipulation, Drawing, and Graphing
885
886 =item *
887 Mail and Usenet News
888
889 =item *
890 Control Flow Utilities (callbacks and exceptions etc)
891
892 =item *
893 File Handle and Input/Output Stream Utilities
894
895 =item *
896 Miscellaneous Modules
897
898 =back
899
900 The registered CPAN sites as of this writing include the following.
901 You should try to choose one close to you:
902
903 =over
904
905 =item *
906 ftp://ftp.sterling.com/programming/languages/perl/
907
908 =item *
909 ftp://ftp.sedl.org/pub/mirrors/CPAN/
910
911 =item *
912 ftp://ftp.uoknor.edu/mirrors/CPAN/
913
914 =item *
915 ftp://ftp.delphi.com/pub/mirrors/packages/perl/CPAN/
916
917 =item *
918 ftp://uiarchive.cso.uiuc.edu/pub/lang/perl/CPAN/
919
920 =item *
921 ftp://ftp.cis.ufl.edu/pub/perl/CPAN/
922
923 =item *
924 ftp://ftp.switch.ch/mirror/CPAN/
925
926 =item *
927 ftp://ftp.sunet.se/pub/lang/perl/CPAN/
928
929 =item *
930 ftp://ftp.ci.uminho.pt/pub/lang/perl/
931
932 =item *
933 ftp://ftp.cs.ruu.nl/pub/PERL/CPAN/
934
935 =item *
936 ftp://ftp.demon.co.uk/pub/mirrors/perl/CPAN/
937
938 =item *
939 ftp://ftp.rz.ruhr-uni-bochum.de/pub/programming/languages/perl/CPAN/
940
941 =item *
942 ftp://ftp.leo.org/pub/comp/programming/languages/perl/CPAN/
943
944 =item *
945 ftp://ftp.pasteur.fr/pub/computing/unix/perl/CPAN/
946
947 =item *
948 ftp://ftp.ibp.fr/pub/perl/CPAN/
949
950 =item *
951 ftp://ftp.funet.fi/pub/languages/perl/CPAN/
952
953 =item *
954 ftp://ftp.tekotago.ac.nz/pub/perl/CPAN/
955
956 =item *
957 ftp://ftp.mame.mu.oz.au/pub/perl/CPAN/
958
959 =item *
960 ftp://coombs.anu.edu.au/pub/perl/
961
962 =item *
963 ftp://dongpo.math.ncu.edu.tw/perl/CPAN/
964
965 =item *
966 ftp://ftp.lab.kdd.co.jp/lang/perl/CPAN/
967
968 =item *
969 ftp://ftp.is.co.za/programming/perl/CPAN/
970
971 =back
972
973 For an up-to-date listing of CPAN sites,
974 see F<http://www.perl.com/perl/CPAN> or F<ftp://ftp.perl.com/perl/>.
975
976 =head1 Modules: Creation, Use, and Abuse
977
978 (The following section is borrowed directly from Tim Bunce's modules
979 file, available at your nearest CPAN site.)
980
981 Perl implements a class using a package, but the presence of a
982 package doesn't imply the presence of a class.  A package is just a
983 namespace.  A class is a package that provides subroutines that can be
984 used as methods.  A method is just a subroutine that expects, as its
985 first argument, either the name of a package (for "static" methods),
986 or a reference to something (for "virtual" methods).
987
988 A module is a file that (by convention) provides a class of the same
989 name (sans the .pm), plus an import method in that class that can be
990 called to fetch exported symbols.  This module may implement some of
991 its methods by loading dynamic C or C++ objects, but that should be
992 totally transparent to the user of the module.  Likewise, the module
993 might set up an AUTOLOAD function to slurp in subroutine definitions on
994 demand, but this is also transparent.  Only the .pm file is required to
995 exist.
996
997 =head2 Guidelines for Module Creation
998
999 =over 4
1000
1001 =item Do similar modules already exist in some form?
1002
1003 If so, please try to reuse the existing modules either in whole or
1004 by inheriting useful features into a new class.  If this is not
1005 practical try to get together with the module authors to work on
1006 extending or enhancing the functionality of the existing modules.
1007 A perfect example is the plethora of packages in perl4 for dealing
1008 with command line options.
1009
1010 If you are writing a module to expand an already existing set of
1011 modules, please coordinate with the author of the package.  It
1012 helps if you follow the same naming scheme and module interaction
1013 scheme as the original author.
1014
1015 =item Try to design the new module to be easy to extend and reuse.
1016
1017 Use blessed references.  Use the two argument form of bless to bless
1018 into the class name given as the first parameter of the constructor,
1019 e.g.,:
1020
1021  sub new {
1022         my $class = shift;
1023         return bless {}, $class;
1024  }
1025
1026 or even this if you'd like it to be used as either a static
1027 or a virtual method.
1028
1029  sub new {
1030         my $self  = shift;
1031         my $class = ref($self) || $self;
1032         return bless {}, $class;
1033  }
1034
1035 Pass arrays as references so more parameters can be added later
1036 (it's also faster).  Convert functions into methods where
1037 appropriate.  Split large methods into smaller more flexible ones.
1038 Inherit methods from other modules if appropriate.
1039
1040 Avoid class name tests like: C<die "Invalid" unless ref $ref eq 'FOO'>.
1041 Generally you can delete the "C<eq 'FOO'>" part with no harm at all.
1042 Let the objects look after themselves! Generally, avoid hardwired
1043 class names as far as possible.
1044
1045 Avoid C<$r-E<gt>Class::func()> where using C<@ISA=qw(... Class ...)> and
1046 C<$r-E<gt>func()> would work (see L<perlbot> for more details).
1047
1048 Use autosplit so little used or newly added functions won't be a
1049 burden to programs which don't use them. Add test functions to
1050 the module after __END__ either using AutoSplit or by saying:
1051
1052  eval join('',<main::DATA>) || die $@ unless caller();
1053
1054 Does your module pass the 'empty sub-class' test? If you say
1055 "C<@SUBCLASS::ISA = qw(YOURCLASS);>" your applications should be able
1056 to use SUBCLASS in exactly the same way as YOURCLASS.  For example,
1057 does your application still work if you change:  C<$obj = new YOURCLASS;>
1058 into: C<$obj = new SUBCLASS;> ?
1059
1060 Avoid keeping any state information in your packages. It makes it
1061 difficult for multiple other packages to use yours. Keep state
1062 information in objects.
1063
1064 Always use B<-w>. Try to C<use strict;> (or C<use strict qw(...);>).
1065 Remember that you can add C<no strict qw(...);> to individual blocks
1066 of code which need less strictness. Always use B<-w>. Always use B<-w>!
1067 Follow the guidelines in the perlstyle(1) manual.
1068
1069 =item Some simple style guidelines
1070
1071 The perlstyle manual supplied with perl has many helpful points.
1072
1073 Coding style is a matter of personal taste. Many people evolve their
1074 style over several years as they learn what helps them write and
1075 maintain good code.  Here's one set of assorted suggestions that
1076 seem to be widely used by experienced developers:
1077
1078 Use underscores to separate words.  It is generally easier to read
1079 $var_names_like_this than $VarNamesLikeThis, especially for
1080 non-native speakers of English. It's also a simple rule that works
1081 consistently with VAR_NAMES_LIKE_THIS.
1082
1083 Package/Module names are an exception to this rule. Perl informally
1084 reserves lowercase module names for 'pragma' modules like integer
1085 and strict. Other modules normally begin with a capital letter and
1086 use mixed case with no underscores (need to be short and portable).
1087
1088 You may find it helpful to use letter case to indicate the scope
1089 or nature of a variable. For example:
1090
1091  $ALL_CAPS_HERE   constants only (beware clashes with perl vars)
1092  $Some_Caps_Here  package-wide global/static
1093  $no_caps_here    function scope my() or local() variables
1094
1095 Function and method names seem to work best as all lowercase.
1096 e.g.,, C<$obj-E<gt>as_string()>.
1097
1098 You can use a leading underscore to indicate that a variable or
1099 function should not be used outside the package that defined it.
1100
1101 =item Select what to export.
1102
1103 Do NOT export method names!
1104
1105 Do NOT export anything else by default without a good reason!
1106
1107 Exports pollute the namespace of the module user.  If you must
1108 export try to use @EXPORT_OK in preference to @EXPORT and avoid
1109 short or common names to reduce the risk of name clashes.
1110
1111 Generally anything not exported is still accessible from outside the
1112 module using the ModuleName::item_name (or C<$blessed_ref-E<gt>method>)
1113 syntax.  By convention you can use a leading underscore on names to
1114 indicate informally that they are 'internal' and not for public use.
1115
1116 (It is actually possible to get private functions by saying:
1117 C<my $subref = sub { ... };  &$subref;>.  But there's no way to call that
1118 directly as a method, because a method must have a name in the symbol
1119 table.)
1120
1121 As a general rule, if the module is trying to be object oriented
1122 then export nothing. If it's just a collection of functions then
1123 @EXPORT_OK anything but use @EXPORT with caution.
1124
1125 =item Select a name for the module.
1126
1127 This name should be as descriptive, accurate, and complete as
1128 possible.  Avoid any risk of ambiguity. Always try to use two or
1129 more whole words.  Generally the name should reflect what is special
1130 about what the module does rather than how it does it.  Please use
1131 nested module names to group informally or categorize a module.
1132 There should be a very good reason for a module not to have a nested name.
1133 Module names should begin with a capital letter.
1134
1135 Having 57 modules all called Sort will not make life easy for anyone
1136 (though having 23 called Sort::Quick is only marginally better :-).
1137 Imagine someone trying to install your module alongside many others.
1138 If in any doubt ask for suggestions in comp.lang.perl.misc.
1139
1140 If you are developing a suite of related modules/classes it's good
1141 practice to use nested classes with a common prefix as this will
1142 avoid namespace clashes. For example:  Xyz::Control, Xyz::View,
1143 Xyz::Model etc. Use the modules in this list as a naming guide.
1144
1145 If adding a new module to a set, follow the original author's
1146 standards for naming modules and the interface to methods in
1147 those modules.
1148
1149 To be portable each component of a module name should be limited to
1150 11 characters. If it might be used on DOS then try to ensure each is
1151 unique in the first 8 characters. Nested modules make this easier.
1152
1153 =item Have you got it right?
1154
1155 How do you know that you've made the right decisions? Have you
1156 picked an interface design that will cause problems later? Have
1157 you picked the most appropriate name? Do you have any questions?
1158
1159 The best way to know for sure, and pick up many helpful suggestions,
1160 is to ask someone who knows. Comp.lang.perl.misc is read by just about
1161 all the people who develop modules and it's the best place to ask.
1162
1163 All you need to do is post a short summary of the module, its
1164 purpose and interfaces. A few lines on each of the main methods is
1165 probably enough. (If you post the whole module it might be ignored
1166 by busy people - generally the very people you want to read it!)
1167
1168 Don't worry about posting if you can't say when the module will be
1169 ready - just say so in the message. It might be worth inviting
1170 others to help you, they may be able to complete it for you!
1171
1172 =item README and other Additional Files.
1173
1174 It's well known that software developers usually fully document the
1175 software they write. If, however, the world is in urgent need of
1176 your software and there is not enough time to write the full
1177 documentation please at least provide a README file containing:
1178
1179 =over 10
1180
1181 =item *
1182 A description of the module/package/extension etc.
1183
1184 =item *
1185 A copyright notice - see below.
1186
1187 =item *
1188 Prerequisites - what else you may need to have.
1189
1190 =item *
1191 How to build it - possible changes to Makefile.PL etc.
1192
1193 =item *
1194 How to install it.
1195
1196 =item *
1197 Recent changes in this release, especially incompatibilities
1198
1199 =item *
1200 Changes / enhancements you plan to make in the future.
1201
1202 =back
1203
1204 If the README file seems to be getting too large you may wish to
1205 split out some of the sections into separate files: INSTALL,
1206 Copying, ToDo etc.
1207
1208 =over 4
1209
1210 =item Adding a Copyright Notice.
1211
1212 How you choose to license your work is a personal decision.
1213 The general mechanism is to assert your Copyright and then make
1214 a declaration of how others may copy/use/modify your work.
1215
1216 Perl, for example, is supplied with two types of license: The GNU
1217 GPL and The Artistic License (see the files README, Copying, and
1218 Artistic).  Larry has good reasons for NOT just using the GNU GPL.
1219
1220 My personal recommendation, out of respect for Larry, Perl, and the
1221 perl community at large is to state something simply like:
1222
1223  Copyright (c) 1995 Your Name. All rights reserved.
1224  This program is free software; you can redistribute it and/or
1225  modify it under the same terms as Perl itself.
1226
1227 This statement should at least appear in the README file. You may
1228 also wish to include it in a Copying file and your source files.
1229 Remember to include the other words in addition to the Copyright.
1230
1231 =item Give the module a version/issue/release number.
1232
1233 To be fully compatible with the Exporter and MakeMaker modules you
1234 should store your module's version number in a non-my package
1235 variable called $VERSION.  This should be a floating point
1236 number with at least two digits after the decimal (i.e., hundredths,
1237 e.g, C<$VERSION = "0.01">).  Don't use a "1.3.2" style version.
1238 See Exporter.pm in Perl5.001m or later for details.
1239
1240 It may be handy to add a function or method to retrieve the number.
1241 Use the number in announcements and archive file names when
1242 releasing the module (ModuleName-1.02.tar.Z).
1243 See perldoc ExtUtils::MakeMaker.pm for details.
1244
1245 =item How to release and distribute a module.
1246
1247 It's good idea to post an announcement of the availability of your
1248 module (or the module itself if small) to the comp.lang.perl.announce
1249 Usenet newsgroup.  This will at least ensure very wide once-off
1250 distribution.
1251
1252 If possible you should place the module into a major ftp archive and
1253 include details of its location in your announcement.
1254
1255 Some notes about ftp archives: Please use a long descriptive file
1256 name which includes the version number. Most incoming directories
1257 will not be readable/listable, i.e., you won't be able to see your
1258 file after uploading it. Remember to send your email notification
1259 message as soon as possible after uploading else your file may get
1260 deleted automatically. Allow time for the file to be processed
1261 and/or check the file has been processed before announcing its
1262 location.
1263
1264 FTP Archives for Perl Modules:
1265
1266 Follow the instructions and links on
1267
1268    http://franz.ww.tu-berlin.de/modulelist
1269
1270 or upload to one of these sites:
1271
1272    ftp://franz.ww.tu-berlin.de/incoming
1273    ftp://ftp.cis.ufl.edu/incoming
1274
1275 and notify upload@franz.ww.tu-berlin.de.
1276
1277 By using the WWW interface you can ask the Upload Server to mirror
1278 your modules from your ftp or WWW site into your own directory on
1279 CPAN!
1280
1281 Please remember to send me an updated entry for the Module list!
1282
1283 =item Take care when changing a released module.
1284
1285 Always strive to remain compatible with previous released versions
1286 (see 2.2 above) Otherwise try to add a mechanism to revert to the
1287 old behaviour if people rely on it. Document incompatible changes.
1288
1289 =back
1290
1291 =back
1292
1293 =head2 Guidelines for Converting Perl 4 Library Scripts into Modules
1294
1295 =over 4
1296
1297 =item There is no requirement to convert anything.
1298
1299 If it ain't broke, don't fix it! Perl 4 library scripts should
1300 continue to work with no problems. You may need to make some minor
1301 changes (like escaping non-array @'s in double quoted strings) but
1302 there is no need to convert a .pl file into a Module for just that.
1303
1304 =item Consider the implications.
1305
1306 All the perl applications which make use of the script will need to
1307 be changed (slightly) if the script is converted into a module.  Is
1308 it worth it unless you plan to make other changes at the same time?
1309
1310 =item Make the most of the opportunity.
1311
1312 If you are going to convert the script to a module you can use the
1313 opportunity to redesign the interface. The 'Guidelines for Module
1314 Creation' above include many of the issues you should consider.
1315
1316 =item The pl2pm utility will get you started.
1317
1318 This utility will read *.pl files (given as parameters) and write
1319 corresponding *.pm files. The pl2pm utilities does the following:
1320
1321 =over 10
1322
1323 =item *
1324 Adds the standard Module prologue lines
1325
1326 =item *
1327 Converts package specifiers from ' to ::
1328
1329 =item *
1330 Converts die(...) to croak(...)
1331
1332 =item *
1333 Several other minor changes
1334
1335 =back
1336
1337 Being a mechanical process pl2pm is not bullet proof. The converted
1338 code will need careful checking, especially any package statements.
1339 Don't delete the original .pl file till the new .pm one works!
1340
1341 =back
1342
1343 =head2 Guidelines for Reusing Application Code
1344
1345 =over 4
1346
1347 =item Complete applications rarely belong in the Perl Module Library.
1348
1349 =item Many applications contain some perl code which could be reused.
1350
1351 Help save the world! Share your code in a form that makes it easy
1352 to reuse.
1353
1354 =item Break-out the reusable code into one or more separate module files.
1355
1356 =item Take the opportunity to reconsider and redesign the interfaces.
1357
1358 =item In some cases the 'application' can then be reduced to a small
1359
1360 fragment of code built on top of the reusable modules. In these cases
1361 the application could invoked as:
1362
1363      perl -e 'use Module::Name; method(@ARGV)' ...
1364 or
1365      perl -mModule::Name ...    (in perl5.002)
1366
1367 =back